package com.letv.ads;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.letv.adlib.managers.status.ad.AdStatusManager;
import com.letv.adlib.managers.status.video.IVideoStatusInformer;
import com.letv.adlib.model.ad.common.AdInfo;
import com.letv.adlib.model.ad.common.VideoCombineBean;
import com.letv.adlib.model.services.CommonAdDataService;
import com.letv.adlib.model.utils.ConfigurationUtil;
import com.letv.adlib.model.utils.UIController;
import com.letv.adlib.sdk.types.AdElement;
import com.letv.adlib.sdk.types.AdElementMime;
import com.letv.adlib.sdk.utils.IPlayerStatusDelegate;
import com.letv.adlib.view.PrerollVideoView;
import com.letv.ads.http.AdsHttpApi;
import com.letv.ads.http.LetvSimpleAsyncTask;
import com.letv.ads.util.AdsUtils;
import com.letv.ads.util.Commons;
import com.letv.ads.util.DataUtils;
import com.letv.ads.util.LogInfo;
import com.letv.ads.view.AdView;
import com.letv.ads.view.AdWebView.AdWebviewEventListener;
import com.letv.ads.view.IAdView.AdMaterialLoadListener;
import com.letv.android.sdk.R;
import com.letv.component.player.Interface.OnVideoViewStateChangeListener;
import com.letv.component.player.LetvMediaPlayerControl;
import com.letv.component.player.LetvVideoViewBuilder;
import com.letv.component.player.videoview.VideoViewH264m3u8;
import com.letv.core.download.image.ImageDownloadStateListener;
import com.letv.core.download.image.ImageDownloader;
import com.letv.core.utils.LetvLogApiTool;
import com.letv.pp.func.CdeHelper;
import com.media.ffmpeg.FFMpegPlayer;
import com.media.ffmpeg.FFMpegPlayer.OnBlockListener;

import java.util.ArrayList;
import java.util.Arrays;

//import com.letv.http.LetvLogApiTool;

@SuppressLint("NewApi")
public class ADPlayFragment extends Fragment implements View.OnClickListener, View.OnTouchListener {
    private static final String TAG = "ADPlayFragment";
    // 无效值
    private static final int INVALID_VALUE = -1;
    // 视频格式
    private static final int FORMAT_NORMAL = 0;// 非拼接的视频格式，包括mp4,3GP等
    private static final int FORMAT_M3U8 = 1;// 拼接的视频格式
    // 直播还是点播
    private static final int TAG_LIVE = 0;
    private static final int TAG_VOD = 1;
    // 播放状态
    private static final int PLAY_STATE_IDLE = 0;
    private static final int PLAY_STATE_LOADING = 1;
    private static final int PLAY_STATE_PLAYING = 2;
    private static final int PLAY_STATE_PAUSED = 3;
    private static final int PLAY_STATE_COMPLETE = 4;
    /**
     * 无广告
     * */
    private static final int NONE = 0;

    /**
     * 前帖视频广告
     * */
    private static final int FRONT_VIDEO = 1;

    /**
     * 前帖图片广告
     * */
    private static final int FRONT_JPG = 2;

    /**
     * 涨停广告
     * */
    private static final int PAUSE = 3;

    /**
     * handler 刷新时间
     * */
    private static final long PERIOD_REFRESH_TIME = 500;
    private static final int MSG_REFRESH_TIME = 0x100;
    private static final int MSG_PREPARE_VIDEO = 0x103;
    private static final int HANDLER_DELAY_LAST_VIDEO = 0x104;
    // 加载广告超时
    private static final int HANDLER_REQUEST_URL_TIMEOUT = 0x105;
    // 空白页，用于释放webview的资源
    private static final String BLANK_URL = "about:blank";
    private boolean isPausing = false;

    /**
     * 根布局
     * */
    private View root;

    /**
     * 视频广告布局
     * */
    private RelativeLayout mVideoViewLayout;

    // 当前播放器的MediaPlayerControl
    private MediaController.MediaPlayerControl mCurrentMediaPlayerControl;
    /**
     * videoview
     * */
    private PrerollVideoView mVideoViewFirst;
    private PrerollVideoView mVideoViewSecond;

    /**
     * 新版播放器
     */
    private LetvMediaPlayerControl letvMediaPlayerControl;
    private boolean isUnionPlay;
    private String mCacheUrl;

    /**
     * 广告时间点队列
     */
    private int[] adsVideoRange;

    /**
     * 各个环节花费时间 0 获取广告数据时间 1 拼接视频所花费的时间 2 CDE数据处理所花费的时间 3 广告起播时间 4 广告加载时间
     */
    private long[] stepsCostTimeArr = new long[5];

    private long readyToPlayTime = 0;

    /**
     * 视频广告点击区
     * */
    private FrameLayout mVideoViewClickLayout;

    /**
     * 图片前帖
     * */
    private ImageView mFrontADImageView;

    /**
     * 静音按钮
     * */
    private ImageView muteView;

    /**
     * 时间
     * */
    private TextView mTimeTextView;

    /**
     * loading圈
     * */
    private View mLoading;
    private View requestLoading;

    /**
     * 暂停广告布局
     * */
    private FrameLayout pauseLayout;
    /**
     * 顶部返回布局
     */
    private RelativeLayout adTopView;
    private Button adTopBackBtn;

    /**
     * 暂停图片
     * */
    /*
     * private ImageView pauseImage;
     */
    /**
     * 暂停view
     * */
    private AdView pauseView;

    /**
     * 暂停广告关闭按钮
     * */
    private View pauseDel;

    /**
     * 前帖广告回调
     * */
    private PlayAdListener adListener;
    private int INIT_TIME_VALUE = -1;
    private int mTimeText = INIT_TIME_VALUE;
    /**
     * 当前的广告无聊
     * */
    // private AdElementMime mPlayAdInfo;

    /**
     * 资源加载开始时间
     */
    protected long loadingStart = 0;

    // /**
    // * 资源加载完成时间
    // */
    // protected long loadingEnd = 0;
    /**
     * 当前时间
     * */
    private int curTime = 0;

    /**
     * 总时间
     * */
    private int totalTime = 0;

    private int totalTimeTmp = 0;

    /**
     * 广告请求时长
     */
    private long adsRequestTime = 0;
    /**
     * 广告加载时长
     */
    private long adsLoadingTime = 0;

    /**
     * 广告拼接花费时长
     */
    private long adsCombineCostTime = 0;

    /**
     * 广告整个交互过程花费时长
     */
    private long adsInteractiveCostTime = 0;
    /**
     * 当前广告类型
     * */
    private int curAdType = NONE;

    /**
     * 当前执行的线程
     * */
    private LetvSimpleAsyncTask curTask;

    /**
     * activity是否已经销毁
     */
    private boolean isDestroy = false;
    /**
     * fragment是否已经添加至activity
     */
    private boolean isReady = false;

    /**
     * 是否广告显示成功
     * */
    private boolean isADShowSucceed = false;

    /**
     * 声音管理者
     * */
    private AudioManager audioManager;

    /**
     * 初始音量
     * */
    private int oldVolume = 0;

    /**
     * 会员去广告按钮
     * */
    private View vipView;

    /**
     * 会员去广告按钮回调
     * */
    private VipViewCallBack viewCallBack;
    /**
     * 已经开始缓冲正片----true
     */
    private boolean isViewCallBack = false;

    /**
     * 开始时间
     * */
    private long startTime;
    /**
     * 半屏2G/3G 暂停显示默认图片
     */
    private View wifiTopViewHalf;

    private RelativeLayout adsBottomView;
    private ImageView adsViewHalfFullBtn;
    private TextView adsDetailsBtn;

    /**
     * 前贴广告是否请求成功
     */
    private boolean isHaveFrontAds = true;

    /**
     * 是否前贴正在进行，如果正在进行则不让重新请求广告
     */
    private boolean isFrontAdProcessing = false;

    /**
     * 广告信息
     */
    private ArrayList<AdElementMime> adsList = null;
    /**
     * 当前正在播放的广告
     */
    private AdElementMime currentAdElementMime = null;
    /**
     * 新增IVideoStatusInformer ，用于客户端将播放状态通知给广告
     */
    private IVideoStatusInformer informer = null;
    /**
     * 当前前贴广告位置
     */
    private int adsItemIndex = 0;
    /**
     * 已经播放完视频时间
     */
    private int adsPlayedTime = 0;
    private boolean isFirstPlayAds = true;
    /**
     * 广告播放第一帧时的时间
     * */
    private long adsPlayFirstFrame;

    /**
     * 广告播放完毕的时间
     * */
    public long adsPlayCompleteTime = 0;

    private RequestDemandFrontAd mRequestDemandFrontAd;

    private String videoVid = "-";

    /**
     * 广告播放地址,多个广告播放地址用;分隔
     * */
    private String adUrls;

    // 整个播放过程中的持续卡顿次数
    private int blockCount = 0;

    // view是否初始化
    private boolean mIsViewInit = false;
    // 用户于联通用户请求
    private boolean mIsWoOrderUser = false;
    private int mTag;
    /**
     * 刷新进度handler
     * */
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (!isReady || isDestroy) {
                return false;
            }
            switch (msg.what) {
                case MSG_REFRESH_TIME:
                    if (isPausing) {
                        break;
                    }
                    if (curTime == 0) {
                        adsPlayFirstFrame = System.currentTimeMillis();
                        if (adListener != null) {
                            adListener.onStartPlay();
                        }
                        LogInfo.log("jc666", "adfirstPlay time=" + adsPlayFirstFrame);
                        if (stepsCostTimeArr[3] == 0) {
                            stepsCostTimeArr[3] = adsPlayFirstFrame - readyToPlayTime;
                            stepsCostTimeArr[4] = adsPlayFirstFrame - loadingStart;
                        }
                    }
                    AdElementMime adElementMime = null;
                    boolean isStandard = false;
                    if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
                        adElementMime = adsList.get(adsItemIndex);
                        if (null != adElementMime
                                && AdElement.CuePointType.Standard.value() == adElementMime.cuePointType) {
                            isStandard = true;
                        }
                    }
                    if (curAdType == FRONT_VIDEO && null != mCurrentMediaPlayerControl) {
                        int time = mCurrentMediaPlayerControl.getCurrentPosition()
                                + (isUnionPlay ? 0 : (adsPlayedTime * 1000));
                        int pos = 0;
                        if (curTime == time && !isPauseAd) {
                            mLoading.setVisibility(View.VISIBLE);
                            blockCount++;
                            if (blockCount >= 1) {
                                LogInfo.log(TAG, "卡顿次数=" + blockCount + " isStandard=" + isStandard);
                                LetvLogApiTool.createPlayLogInfo("广告卡顿", videoVid, "  广告连续卡顿次数:" + blockCount);
                            }
                            if (blockCount >= 3) {
                                if (mTimeText > 0) {
                                    if (null != mCurrentMediaPlayerControl && blockCount == 3) {
                                        // 3次卡顿都没有继续播放的话则调下start
                                        LogInfo.log(TAG, "_+_+_+)_+try to start!");
                                        mCurrentMediaPlayerControl.start();
                                    }
                                }
                                if ((mTimeText <= 0 && !isStandard) || blockCount > 10) {
                                    // 起播卡顿3次或者非起播卡顿次数太多,直接超时处理
                                    handler.sendEmptyMessage(HANDLER_REQUEST_URL_TIMEOUT);
                                    blockCount = 0;
                                    break;
                                }
                            }
                        } else {
                            LogInfo.log(TAG, "非卡顿");
                            blockCount = 0;
                            if (time <= 0 && curTime > 0) {
                                if (!isPauseAd) {
                                    mLoading.setVisibility(View.VISIBLE);
                                }
                            } else {
                                mLoading.setVisibility(View.GONE);
                            }
                            if (isFirstPlayAds) {
                                isFirstPlayAds = false;
                                adsLoadingTime = System.currentTimeMillis() - adsLoadingTime;
                                if (isLandscape()) {
                                    zoomViewFull(getCurrentWorkingVideoView());
                                } else {
                                    zoomView(320, 180, getCurrentWorkingVideoView());
                                }
                            }
                            curTime = time;
                        }
                        LogInfo.log(TAG, " has played " + time + "ms," + curTime + "ms,total=" + totalTime
                                + "s,isPlayingIndex=" + adsItemIndex + " hasPlayed:" + adsPlayedTime);
                        pos = totalTime * 1000 - curTime;
                        if (pos < 0) {
                            pos = 0;
                        }
                        if ((INIT_TIME_VALUE == mTimeText || (mTimeText >= 0 && (curTime - adsPlayedTime * 1000) > 0))) {
                            mTimeText = pos / 1000;
                        }
                        mTimeTextView.setText(mTimeText + "");
                        handler.sendEmptyMessageDelayed(MSG_REFRESH_TIME, PERIOD_REFRESH_TIME);
                    } else if (curAdType == FRONT_JPG) {
                        int pos = totalTime - curTime;
                        if (pos <= 0) {
                            pos = 0;
                        }
                        mTimeText = pos;
                        mTimeTextView.setText(mTimeText + "");
                        if (pos == 0) {
                            /**
                             * ` 完成统计
                             * */
                            if (mCurAdStatusManager != null) {
                                mCurAdStatusManager.onAdPlayComplete();
                            }
                            FrontAdFinish();
                            return false;
                        }
                        curTime++;
                        handler.sendEmptyMessageDelayed(MSG_REFRESH_TIME, 1000);
                    }
                    break;
                case MSG_PREPARE_VIDEO:
                    int bufferPercentage = 0;
                    AdElementMime currentAD = null;
                    if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
                        currentAD = adsList.get(adsItemIndex);
                    }
                    if (null != currentAD && !TextUtils.isEmpty(currentAD.localPath)) {
                        // 本地视频没有缓冲进度
                        bufferPercentage = 100;
                    } else if (null != mCurrentMediaPlayerControl) {
                        bufferPercentage = mCurrentMediaPlayerControl.getBufferPercentage();
                    }
                    LogInfo.log(TAG, "isFirstVideoViewWorking =" + (mCurrentMediaPlayerControl == mVideoViewFirst)
                            + " bufferPercentage = " + bufferPercentage);
                    if (bufferPercentage >= 100) {
                        if (handler != null) {
                            handler.removeMessages(MSG_PREPARE_VIDEO);
                        }
                        // 当前视频缓冲完毕，下一个视频准备好播放状态,便于快速起播
                        whichVideoViewToPlay(isDelayFirstVideoView, delayAdItem, true);
                    } else {
                        if (handler != null) {
                            handler.sendEmptyMessageDelayed(MSG_PREPARE_VIDEO, 2000);
                        }
                    }
                    break;
                case HANDLER_DELAY_LAST_VIDEO:
                    int bufferPercentageLast = 0;
                    if (null != mCurrentMediaPlayerControl) {
                        bufferPercentageLast = mCurrentMediaPlayerControl.getBufferPercentage();
                    }
                    LogInfo.log(TAG, "mTimeText =" + mTimeText + " isFirstVideoViewWorking ="
                            + (mCurrentMediaPlayerControl == mVideoViewFirst) + " bufferPercentageLast = "
                            + bufferPercentageLast);
                    if (bufferPercentageLast >= 100) {
                        if (adsList != null && adsList.size() <= (adsItemIndex + 1)) {// 告诉主客户端可以缓冲视频了
                            if (handler != null) {
                                handler.removeMessages(HANDLER_DELAY_LAST_VIDEO);
                            }
                            LogInfo.log(TAG, "------------->-last---adsItemIndex =" + adsItemIndex);
                            if (viewCallBack != null && !isViewCallBack) {// 告诉主客户端,开始缓冲
                                isViewCallBack = true;
                                stopCdeBuffer();
                                viewCallBack.getMainClientBackGroundStart();
                            }
                        } else {
                            if (handler != null) {
                                handler.sendEmptyMessageDelayed(HANDLER_DELAY_LAST_VIDEO, 1000);
                            }
                        }
                    } else {
                        if (handler != null) {
                            handler.sendEmptyMessageDelayed(HANDLER_DELAY_LAST_VIDEO, 2000);
                        }
                    }
                    break;
                case HANDLER_REQUEST_URL_TIMEOUT:
                    LogInfo.log(TAG, "--load video timeout!!!--");
                    LetvLogApiTool.createPlayLogInfo("广告加载超时", "videoVid", "...");
                    if (isUnionPlay) {
                        handleM3U8PlayError();
                    } else {
                        handleNormalVideoPlayError(mCurrentMediaPlayerControl == mVideoViewFirst);
                    }
                    break;
            }
            return false;
        }
    });

    /**
     * 根据贴片类型和播放状态素材类型，处理UI
     * 
     * @param ct
     * @param state
     * @param mediaType
     */
    private void handleUI(int ct, int state, int mediaType) {
        LogInfo.log(TAG, "handleUI ct=" + ct + "  state=" + state + " mediaType=" + mediaType);
        if (!mIsViewInit) {
            return;
        }
        switch (state) {
            case PLAY_STATE_LOADING: {
                mVideoViewLayout.setVisibility(View.VISIBLE);
                mLoading.setVisibility(View.VISIBLE);
                muteView.setVisibility(View.GONE);
                mTimeTextView.setVisibility(View.GONE);
                adsBottomView.setVisibility(View.GONE);
                vipView.setVisibility(View.GONE);
                mFrontADImageView.setVisibility(View.GONE);
                break;
            }
            case PLAY_STATE_PLAYING:
            case PLAY_STATE_PAUSED: {
                boolean isStandard = (AdElement.CuePointType.Standard.value() == ct);
                mVideoViewLayout.setVisibility(View.VISIBLE);
                mLoading.setVisibility(View.GONE);
                adsBottomView.setVisibility(View.VISIBLE);
                mTimeTextView.setVisibility(isStandard ? View.GONE : View.VISIBLE);
                adsDetailsBtn.setVisibility(isStandard ? View.GONE : View.VISIBLE);
//                vipView.setVisibility(isStandard ? View.GONE : View.VISIBLE);
                mFrontADImageView.setVisibility((FRONT_JPG == mediaType) ? View.VISIBLE : View.GONE);
                if (FRONT_JPG != mediaType) {
                    muteView.setVisibility(View.VISIBLE);
                    int curVoice = 0;
                    if (audioManager != null) {
                        curVoice = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    }
                    if (curVoice <= 0) {
                        muteView.setImageResource(R.drawable.letv_ad_mute);
                    } else {
                        muteView.setImageResource(R.drawable.letv_ad_not_muted);
                    }
                } else {
                    muteView.setVisibility(View.GONE);
                }
                break;
            }
            case PLAY_STATE_COMPLETE: {
                mLoading.setVisibility(View.GONE);
                mTimeTextView.setText(null);
                mTimeTextView.setVisibility(View.GONE);
                vipView.setVisibility(View.GONE);
                mVideoViewLayout.setVisibility(View.GONE);
                mFrontADImageView.setImageDrawable(null);
                mFrontADImageView.setVisibility(View.GONE);
                mVideoViewLayout.setVisibility(View.GONE);
                muteView.setVisibility(View.GONE);
                adsBottomView.setVisibility(View.GONE);
                if (audioManager != null) {
                    int cur = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    if (cur == 0) {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, oldVolume, 0);
                        muteView.setImageResource(R.drawable.letv_ad_not_muted);
                    }
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    private void switchVideoAdItem(int curAdIndex) {
        LogInfo.log(TAG, "switchVideoAdItem curAdIndex=" + curAdIndex + " adsItemIndex=" + adsItemIndex);
        if (adsList == null) {
            adsList = new ArrayList<AdElementMime>();
        }
        if (adsList.size() > 0 && curAdIndex <= adsList.size()) {
            AdElementMime lastItem = null, curItem = null;
            if (curAdIndex <= 0 && adsItemIndex == 0) {
                // 播放器有时给的index不对,过滤掉错误的
                curItem = adsList.get(0);
                exposureStatistics(curItem);
                adsItemIndex = curAdIndex;
                adsPlayedTime = 0;
            } else if (adsItemIndex < curAdIndex) {
                // 播放器有时给的index不对,过滤掉错误的
                lastItem = adsList.get(curAdIndex - 1);
                LogInfo.log(TAG, "switch curAdIndex=" + curAdIndex + ",dur=" + lastItem.duration);
                curItem = adsList.get(curAdIndex);
                // 上一个视频播放完成上报
                completeStatistics(lastItem);
                // 当前视频播放完成上报
                exposureStatistics(curItem);
                int hasPlayedTime = 0;
                for (int i = 0; i < curAdIndex; ++i) {
                    hasPlayedTime += adsList.get(i).duration;
                }
                adsPlayedTime = hasPlayedTime;
                adsItemIndex = curAdIndex;
                LogInfo.log(TAG, "switchVideoAdItem adsPlayedTime=" + adsPlayedTime);
            } else {
                LogInfo.log(TAG, "arguments error curAdIndex=" + curAdIndex + ",adsPlayedTime" + adsPlayedTime
                        + ",adsItemIndex=" + adsItemIndex + ",total=" + adsList.size());
            }
            if (null != curItem) {
                handleUI(curItem.cuePointType, PLAY_STATE_PLAYING, FRONT_VIDEO);
                currentAdElementMime = curItem;
            }
        } else {
            LogInfo.log(TAG, "arguments error curAdIndex=" + curAdIndex + ",but ad'size is " + adsList.size());
        }
    }

    /**
     * 当前广告的统计工具
     * */
    private AdStatusManager mCurAdStatusManager;
    /**
     * 非拼接视频会提前缓冲下一个广告，期间会有加载完成，播放错误(可能出现)的统计
     * */
    private AdStatusManager mBufferAdStatusManager;

    private boolean isPauseAd = false;

    /**
     * 倒计时字体
     */
    private Typeface mTypeface;

    /**
     * 是否处于锁屏状态
     */
    private boolean isLockedScreen;
    /**
     * 三星手机S3
     */
    private boolean isGTXS3 = false;

//    private IWoFlowManager woFlowManager;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            if (audioManager.getMode() == AudioManager.MODE_INVALID) {
                audioManager.setMode(AudioManager.MODE_NORMAL);
            }
        }

//        Class clazz_wfm = JarLoader.loadClass(getActivity(), JarConstant.LETV_WO_NAME, JarConstant.LETV_WO_PACKAGENAME,
//                "WoFlowManager");
//        woFlowManager = (IWoFlowManager) JarLoader.invokeStaticMethod(clazz_wfm, "getInstance", null, null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.letv_ad_play, null, false);
        findView();
        LogInfo.log(TAG, "onCreateView");
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 通知该碎片已经结束，需要进行清理操作
        LetvLogApiTool.createPlayLogInfo("销毁广告界面", videoVid, "...");
        notifyAdHadClosed();
        LogInfo.log(TAG, "---onDestroy,adStatusManager=" + (mCurAdStatusManager == null) + ","
                + (mBufferAdStatusManager == null));
        iPlayerStatusDelegate = null;
    }

    /**
     * 通知广告本Fragment已经销毁了
     */
    private void notifyAdHadClosed() {
        try {
            if (stepsCostTimeArr[0] != 0) {
                CommonAdDataService.writeDebugLog("steps cost time:||" + Arrays.toString(stepsCostTimeArr) + "||");
                stepsCostTimeArr = new long[5];
            }

            if (mCurAdStatusManager != null) {
                mCurAdStatusManager.onAdClosed();
                mCurAdStatusManager = null;
            }
            if (mBufferAdStatusManager != null) {
                mBufferAdStatusManager.onAdClosed();
                mBufferAdStatusManager = null;
            }

        } catch (Exception e) {
        }
    }

    /**
     * 离线视频不显示顶部返回 跟 底部 半屏按钮
     */
    public void setOfflineViewHide() {
        // 经与产品人员沟通，没有半屏播放状态的情况下，可以没有“切屏”按钮，播放广告过程中，
        // 可以通过点击android手机的返回键返回到上一层。因IOS系统没有返回键，所以播放广
        // 告过程中必须加上返回按钮，现为了两个系统统一，故android也应加上返回按钮。
        // if(adTopView != null){
        // adTopView.setVisibility(View.GONE);
        // }
        if (adsViewHalfFullBtn != null) {
            adsViewHalfFullBtn.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 顶部返回键显示
     * 
     * @param isVisible
     */
    public void setAdTopViewVisible(boolean isVisible) {
        if (adTopView != null) {
            adTopView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 初始化控件
     * */
    private void findView() {
        mVideoViewLayout = (RelativeLayout) root.findViewById(R.id.ad_video_layout);
        mVideoViewFirst = (PrerollVideoView) root.findViewById(R.id.ad_video_first);
        mVideoViewSecond = (PrerollVideoView) root.findViewById(R.id.ad_video_second);
        mVideoViewClickLayout = (FrameLayout) root.findViewById(R.id.ad_video_click);
        mFrontADImageView = (ImageView) root.findViewById(R.id.ad_image);
        mTimeTextView = (TextView) root.findViewById(R.id.ad_time);
        mLoading = root.findViewById(R.id.ad_loading_layout);
        requestLoading = root.findViewById(R.id.request_loading);
        pauseLayout = (FrameLayout) root.findViewById(R.id.pause_layout);
        pauseDel = root.findViewById(R.id.pause_del);
        pauseView = (AdView) root.findViewById(R.id.pause_view);
        muteView = (ImageView) root.findViewById(R.id.ad_mute);
        vipView = root.findViewById(R.id.ad_vip);
        wifiTopViewHalf = root.findViewById(R.id.wifiTopViewHalfAd);
        adsBottomView = (RelativeLayout) root.findViewById(R.id.ad_bottom_view);
        adsViewHalfFullBtn = (ImageView) root.findViewById(R.id.ad_view_disp);
        adsDetailsBtn = (TextView) root.findViewById(R.id.ad_details);

        adTopView = (RelativeLayout) root.findViewById(R.id.ad_Top_view);
        adTopBackBtn = (Button) root.findViewById(R.id.ad_view_back);

        videoViewInit();
        pauseDel.setOnClickListener(this);
        if (audioManager != null) {// 初始化声音管理器
            int cur = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (cur == 0) {
                muteView.setImageResource(R.drawable.letv_ad_mute);
            } else {
                muteView.setImageResource(R.drawable.letv_ad_not_muted);
            }
        }
        muteView.setOnClickListener(this);

        vipView.setOnClickListener(this);
        wifiTopViewHalf.setOnClickListener(this);
        adsViewHalfFullBtn.setOnClickListener(this);
        adTopBackBtn.setOnClickListener(this);
        mTypeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/ads_digital.ttf");
        mTimeTextView.setTypeface(mTypeface);
        mVideoViewClickLayout.setOnTouchListener(this);
        adsDetailsBtn.setOnClickListener(this);
        mFrontADImageView.setOnClickListener(this);
        mIsViewInit = true;
    }

    /**
     * 设置广告声音图标显示
     *
     * @param cur
     */
    public void setMuteViewStatus(int cur) {
        if (muteView != null && !isDestroy) {
            if (cur <= 0) {
                muteView.setImageResource(R.drawable.letv_ad_mute);
            } else {
                muteView.setImageResource(R.drawable.letv_ad_not_muted);
            }
        }
    }

    /**
     * 设置半屏全屏图标显示
     *
     * @param isHalf
     */
    public void setHalfFullStatus(boolean isHalf) {
        if (adsViewHalfFullBtn != null && !isDestroy) {
            if (isHalf) {
                adsViewHalfFullBtn.setImageResource(R.drawable.letv_ad_full_selecter);
            } else {
                adsViewHalfFullBtn.setImageResource(R.drawable.letv_ad_half_selecter);
            }
        }
    }

    /**
     * 全屏播放设置改按钮隐藏
     * 
     * @param isToVisible
     */
    public void setAdsViewHalfFullBtnVisible(boolean isToVisible) {
        if (adsViewHalfFullBtn != null) {
            adsViewHalfFullBtn.setVisibility(isToVisible ? View.VISIBLE : View.INVISIBLE);
        }
    }

    /**
     * 播放器初始化
     */
    private void videoViewInit() {
        mVideoViewSecond.setZOrderOnTop(true);
        mVideoViewSecond.setZOrderMediaOverlay(true);
        mVideoViewFirst.setZOrderOnTop(true);
        mVideoViewFirst.setZOrderMediaOverlay(true);
        letvMediaPlayerControl =
                LetvVideoViewBuilder.getInstants().build(getActivity().getApplicationContext(),
                LetvVideoViewBuilder.Type.MOBILE_H264_M3U8);
        SurfaceView surfaceView = (SurfaceView) letvMediaPlayerControl.getView();
        // surfaceView.setBackgroundColor(Color.argb(150,255,0,0));

        FrameLayout.LayoutParams lytp = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        lytp.gravity = Gravity.CENTER;
        surfaceView.setLayoutParams(lytp);

        mVideoViewClickLayout.addView(surfaceView, lytp);
        // surfaceView.setla
        surfaceView.setVisibility(View.GONE);
        surfaceView.setZOrderOnTop(true);
        surfaceView.setZOrderMediaOverlay(true);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (isLandscape()) {
            zoomViewFull(root);
            zoomView(217, 123, pauseLayout);
            setHalfFullStatus(false);
            if (adTopView != null) {
                adTopView.setVisibility(View.VISIBLE);
            }
        }
        else {
            zoomView(320, 180, root);
            zoomView(270, 152, pauseLayout);
            setHalfFullStatus(true);
            if (adTopView != null) {
                adTopView.setVisibility(View.VISIBLE);
            }
        }

        isReady = true;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        boolean isLandScape = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
        int pauseLayoutIsVisiable = pauseLayout.getVisibility();
        LogInfo.log(TAG, "onConfigurationChanged isLandScape=" + isLandScape);
        if (isLandScape) {
            zoomViewFull(root);
            zoomViewFull(getCurrentWorkingVideoView());
            if (pauseLayoutIsVisiable != View.VISIBLE && curAdType == PAUSE) {
                pauseLayout.setVisibility(View.VISIBLE);
            }
            zoomView(217, 123, pauseLayout);
            setHalfFullStatus(false);
            /*
             * if(adTopView != null ) { adTopView.setVisibility(View.VISIBLE); }
             */
        } else {
            zoomView(320, 180, root);
            zoomView(320, 180, getCurrentWorkingVideoView());
            if (pauseLayoutIsVisiable == View.VISIBLE) {
                pauseLayout.setVisibility(View.GONE);
            }
            zoomView(270, 152, pauseLayout);
            setHalfFullStatus(true);
        }
        if (isPauseAd) {
            mLoading.setVisibility(View.GONE);
            if (isLandScape) {
                setwifiTopViewVisible(false);
                if (vipView != null) {
                    vipView.setVisibility(View.GONE);
                }
                if (adsBottomView != null) {
                    adsBottomView.setVisibility(View.GONE);
                }
            } else {
                if (isPauseAd) {
                    setwifiTopViewVisible(true);
                } else {
                    setwifiTopViewVisible(false);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogInfo.log(TAG, "ads--xxxxxxxxx--onResume");
        resume();
    }

    private void resume() {
        LogInfo.log(TAG, "resume() curAdType=" + curAdType + " isPauseAd=" + isPauseAd);
        isPausing = false;
        // if (isLockedScreen) {
        // return;
        // }
        if (curAdType == FRONT_JPG) {
            startRefreshTime();
            /**
             * 继续统
             * */
            if (mCurAdStatusManager != null) {
                mCurAdStatusManager.onAdResumed();
            }
        } else if (curAdType == FRONT_VIDEO) {
            if (!isPauseAd) {

                mTimeTextView.setText(mTimeText + "");
                setwifiTopViewVisible(false);
                int hasPlayTime = isUnionPlay ? curTime
                        : (curTime >= adsPlayedTime * 1000 ? (curTime - adsPlayedTime * 1000) : 0);
                LogInfo.log(TAG, " resume to play at " + hasPlayTime + "  isUnionPlay=" + isUnionPlay + " curTime="
                        + curTime);
                int lastSeekWhenDestoryed = 0;
                if (mCurrentMediaPlayerControl instanceof LetvMediaPlayerControl) {
                    lastSeekWhenDestoryed = ((LetvMediaPlayerControl) mCurrentMediaPlayerControl)
                            .getLastSeekWhenDestoryed();
                }
                int seekTo = (lastSeekWhenDestoryed != 0) ? lastSeekWhenDestoryed : hasPlayTime;
                LogInfo.log(TAG, "resume lastSeekWhenDestoryed= " + lastSeekWhenDestoryed + " seekTo=" + seekTo);
                if (null != mCurrentMediaPlayerControl) {
                    if (isFrontAdProcessing) {
                        LetvLogApiTool.createPlayLogInfo("广告返回前台", videoVid, " 需要拖动的进度是" + seekTo);
                    }
                    mCurrentMediaPlayerControl.seekTo(seekTo);
                    mCurrentMediaPlayerControl.start();
                    startRefreshTime();
                }
                /**
                 * 继续统计
                 * */
                if (mCurAdStatusManager != null) {
                    mCurAdStatusManager.onAdResumed();
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (curAdType == FRONT_JPG || curAdType == FRONT_VIDEO) {
            /**
             * 暂停统计
             * */
            if (mCurAdStatusManager != null) {
                mCurAdStatusManager.onAdPaused();
                // //LogInfo.log(TAG, "--------onPause--暂停统计----------");
            }
        }
        if (isFrontAdProcessing && mCurrentMediaPlayerControl != null) {
            int hasPlayTime = isUnionPlay ? curTime
                    : (curTime >= adsPlayedTime * 1000 ? (curTime - adsPlayedTime * 1000) : 0);
            LetvLogApiTool.createPlayLogInfo("广告即将退出前台", videoVid, " 播放的进度是" + hasPlayTime);
        }
        pause();
        // mTimeText = mTimeTextView.getText().toString();
        LogInfo.log(TAG, "----onPause----FRONT_MP4--curTime=" + curTime + "   mTimeText =" + mTimeText);
    }

    @Override
    public void onDestroyView() {// 做一些必要的消耗
        super.onDestroyView();
        stopCdeBuffer();
        mIsViewInit = false;
        LogInfo.log(TAG, "onDestroyView");
        isDestroy = true;
        isReady = false;
        mOnErrorListenerFirst = null;
        mOnErrorListenerSecond = null;
        mCurrentMediaPlayerControl = null;
        mVideoViewFirst = null;
        mVideoViewSecond = null;
        letvMediaPlayerControl = null;
        stopRefreshTime();
        if (curTask != null) {
            curTask.cancel(true);
        }
        curTask = null;
    }

    public VipViewCallBack getViewCallBack() {
        return viewCallBack;
    }

    public void setViewCallBack(VipViewCallBack viewCallBack) {
        this.viewCallBack = viewCallBack;
    }

    /**
     * 播放第一个非拼接视频,兼容在线与本地播放器
     * */
    private boolean playFirstVideo(final AdElementMime adInfo) {
        blockCount = 0;
        if (!TextUtils.isEmpty(adInfo.mediaFileUrl)) {
            handleUI(adInfo.cuePointType, isPauseAd ? PLAY_STATE_IDLE : PLAY_STATE_LOADING, FRONT_VIDEO);
            adUrls = adInfo.mediaFileUrl;
            mCurrentMediaPlayerControl = mVideoViewFirst;
            setVideoViewParameter(mVideoViewFirst, adInfo.mediaFileUrl, true);
            mVideoViewFirst.setVisibility(View.VISIBLE);
            if (!isPauseAd) {
                mVideoViewFirst.start();
                handler.sendEmptyMessageDelayed(HANDLER_REQUEST_URL_TIMEOUT, 10000);
            } else {
                mVideoViewFirst.pause();
            }
            return true;
        } else {
            FrontAdFinish();
            return false;
        }
    }

    /**
     * 播放M3U8(拼接)
     * 
     * @param m3u8VideoUrl
     */
    private boolean playM3U8(String m3u8VideoUrl) {
        LogInfo.log(TAG, "playM3U8 m3u8VideoUrl=" + m3u8VideoUrl + "  isPauseAd=" + isPauseAd);
        if (letvMediaPlayerControl != null && !TextUtils.isEmpty(m3u8VideoUrl)) {
            mCurrentMediaPlayerControl = letvMediaPlayerControl;
            handleUI(AdElement.CuePointType.PreRoll.value(), isPauseAd ? PLAY_STATE_IDLE : PLAY_STATE_LOADING,
                    FRONT_VIDEO);
            letvMediaPlayerControl.setVideoPath(m3u8VideoUrl);
            letvMediaPlayerControl.setOnErrorListener(mOnErrorListenerM3U8);
            letvMediaPlayerControl.setOnPreparedListener(mOnPreparedListenerM3U8);
            letvMediaPlayerControl.setOnCompletionListener(onCompletionListenerM3U8);
            letvMediaPlayerControl.setOnAdNumberListener(onSwitchVideoAdListener);
            letvMediaPlayerControl.setOnBlockListener(new OnBlockListener() {

                @Override
                public void onBlock(FFMpegPlayer arg0, int arg1) {
                    LogInfo.log(TAG, "onBlock arg1=" + arg1);
                    if (null != currentAdElementMime) {
                        if (FFMpegPlayer.MEDIA_BLOCK_START == arg1) {
                            blockStatistics(currentAdElementMime);
                        } else if (FFMpegPlayer.MEDIA_BLOCK_END == arg1) {
                            blockEndStatistics(currentAdElementMime);
                        }
                    }
                }
            });
            letvMediaPlayerControl.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    LogInfo.log(TAG, "buffer percent " + percent + "%");
                    if (percent >= 100) {
                        if (viewCallBack != null && !isViewCallBack) {
                            isViewCallBack = true;
                            // stopCdeBuffer();
                            viewCallBack.getMainClientBackGroundStart();
                            letvMediaPlayerControl.setOnBufferingUpdateListener(null);
                            LogInfo.log(TAG, "begin request buffer 100%. start at " + System.currentTimeMillis());
                        }
                    }
                }
            });
            letvMediaPlayerControl.setVideoViewStateChangeListener(new OnVideoViewStateChangeListener() {
                @Override
                public void onChange(int i) {
                    LogInfo.log(TAG, "onChange i=" + i);
                    if (i == VideoViewH264m3u8.STATE_PLAYING) {
                        // LogInfo.log(TAG,"----onDisplay");
                        mLoading.setVisibility(View.GONE);
                    }
                }
            });
            LogInfo.log("cost", "give url cost =" + (System.currentTimeMillis() - loadingStart));
            if (!isPauseAd) {
                letvMediaPlayerControl.start();
                handler.sendEmptyMessageDelayed(HANDLER_REQUEST_URL_TIMEOUT, 10000);
            } else {
                letvMediaPlayerControl.pause();
            }
            return true;
        } else {
            FrontAdFinish();
            return false;
        }
    }

    /**
     * 跳过视频广告
     * */
    public void stopFrontAd() {
        switch (curAdType) {
            case FRONT_VIDEO:
                mVideoViewFirst.stopPlayback();
                mVideoViewSecond.stopPlayback();
            case FRONT_JPG: {
                stopRefreshTime();
                FrontAdFinish();
                break;
            }
        }
    }

    /**
     * 暂停
     * */
    public void pause() {
        if (mCurrentMediaPlayerControl != null) {
            isPausing = true;
            // LogInfo.log(TAG,"mediaPlayerControl != null--"+(mediaPlayerControl
            // != null));
            mCurrentMediaPlayerControl.pause();
            stopRefreshTime();
        }
    }

    public void setADPause(boolean pauseAd) {
        LogInfo.log(TAG, "-----setADPause=" + pauseAd);
        if (pauseAd) {
            pause();
        } else {
            if (isPauseAd && totalTime > 0) {
                isPauseAd = false;
                setwifiTopViewVisible(false);
                mLoading.setVisibility(View.VISIBLE);
                if (null != mCurrentMediaPlayerControl) {
                    mCurrentMediaPlayerControl.start();
                    mCurrentMediaPlayerControl
                            .seekTo(curTime >= adsPlayedTime * 1000 ? (curTime - adsPlayedTime * 1000) : 0);
                    startRefreshTime();
                }
                if (mCurAdStatusManager != null) {
                    mCurAdStatusManager.onAdResumed();
                }
            }
        }
    }

    /**
     * @return the isPauseAd
     */
    public boolean isPauseAd() {
        return isPauseAd;
    }

    /**
     * @param isPauseAd
     * the isPauseAd to set
     */
    public void setPauseAd(boolean isPauseAd) {
        this.isPauseAd = isPauseAd;
        setMobileNetBg(isPauseAd);
    }

    /**
     * @return the isHaveFrontAds
     */
    public boolean isHaveFrontAds() {
        return isHaveFrontAds;
    }

    /**
     * @param isHaveFrontAds
     * the isHaveFrontAds to set
     */
    public void setHaveFrontAds(boolean isHaveFrontAds) {
        this.isHaveFrontAds = isHaveFrontAds;
    }

    /**
     * 显示隐藏 2G/3G 暂停播放 默认图片
     *
     * @param disp
     */
    public void setMobileNetBg(boolean disp) {
        if (mLoading == null) {
            LogInfo.log(TAG, "解决首页的崩溃，但是怎么能走到这呢？奇怪？？？？");
            return;
        }
        if (isLandscape()) {
            mLoading.setVisibility(View.GONE);
            setwifiTopViewVisible(false);
            if (vipView != null) {
                vipView.setVisibility(View.GONE);
            }
            if (adsBottomView != null) {
                adsBottomView.setVisibility(View.GONE);
            }
        } else {
            if (disp) {
                mLoading.setVisibility(View.GONE);
            } else {
                mLoading.setVisibility(View.VISIBLE);
            }
            setwifiTopViewVisible(disp);
        }
    }

    private void setwifiTopViewVisible(boolean isVisable) {
        if (isVisable) {
            if (vipView != null) {
                vipView.setVisibility(View.GONE);
            }
            if (adsBottomView != null) {
                adsBottomView.setVisibility(View.GONE);
            }
        } else {
            if (vipView != null) {
                boolean isStandard = false;
                if (null != currentAdElementMime) {
                    isStandard = (AdElement.CuePointType.Standard.value() == currentAdElementMime.cuePointType);
                }
                // 标版不展示跳过广告
//                vipView.setVisibility(isStandard ? View.GONE : View.VISIBLE);
            }
            if (adsBottomView != null) {
                adsBottomView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 停止
     * */
    public void stopPlayback() {
        stopPlayback(false);
    }

    /**
     * 停止播放，用于播放器通知停止广告
     * 
     * @param notifyOnFinish
     * 是否需要通知finish，一般情况下不需要，只有在会员跳过的时候需要
     */
    public void stopPlayback(boolean notifyOnFinish) {
        LogInfo.log(TAG, "stopPlayback notifyOnFinish=" + notifyOnFinish);
        if (mCurAdStatusManager != null) {
            mCurAdStatusManager.onAdStoped();
        }
        FrontAdFinish(!notifyOnFinish);
        if (curTask != null) {
            curTask.cancel(true);
        }
    }

    /**
     * 跳到
     * */
    public void seekTo(int msec) {
        if (null != mCurrentMediaPlayerControl) {
            mCurrentMediaPlayerControl.seekTo(msec);
        }
    }

    /**
     * 是否在播放中
     * */
    public boolean isPlaying() {
        if (null != mCurrentMediaPlayerControl) {
            return mCurrentMediaPlayerControl.isPlaying();
        }
        return false;
    }

    /**
     * 得到当前时间点
     * */
    public int getCurrentPosition() {
        if (null != mCurrentMediaPlayerControl) {
            return mCurrentMediaPlayerControl.getCurrentPosition();
        }
        return 0;
    }

    /**
     * 得到当前缓冲时间点
     * */
    public int getBufferPercentage() {
        if (null != mCurrentMediaPlayerControl) {
            return mCurrentMediaPlayerControl.getBufferPercentage();
        }
        return 0;
    }

    /**
     * 得到广告listener
     * */
    public PlayAdListener getAdListener() {
        return adListener;
    }

    /**
     * 设置广告listener
     * */
    public void setAdListener(PlayAdListener adListener) {
        this.adListener = adListener;
    }

    /**
     * 前贴广告任务
     *
     * @param context
     * @param cid
     * @param aid
     * @param vid
     * @param mmsid
     * @param uuid
     * @param uid
     * @param vlen
     * @param py
     * @param ty
     * @param isSupportM3U8
     */
    private void startRequestFrontAdTask(Context context, boolean isWoOrder, int cid, long aid, long vid, String mmsid,
            String streamUrl, String uuid, String uid, String vlen, String py, String ty, boolean isSupportM3U8,
            boolean isNeedPay, boolean disableAvd, boolean toShowLoading, boolean isHotVideo, boolean isOfflineVideo,
            boolean isOpenCde, boolean isLive,boolean isPanorama) {
        LogInfo.log(TAG, "startRequestFrontAdTask");
        startTime = System.currentTimeMillis();
        if (isDestroy) {
            return;
        }
        adsPlayCompleteTime = adsLoadingTime = 0;
        loadingStart = System.currentTimeMillis();
        LogInfo.log(TAG, "begin  request front ad. start at " + loadingStart + ",isFrontAdProcessing="
                + isFrontAdProcessing);
        if (isFrontAdProcessing) {
            LogInfo.log(TAG, "front ad repeat request");
            return;
        }
        isFrontAdProcessing = true;
        cancelRequestFrontAdTask();
        mRequestDemandFrontAd = new RequestDemandFrontAd(context, isWoOrder, cid, aid, vid, mmsid,
                streamUrl, uuid, uid, vlen, py, ty, isSupportM3U8, isNeedPay, disableAvd,
                toShowLoading, isHotVideo,
                isOfflineVideo, isOpenCde, isLive, isPanorama);
        mRequestDemandFrontAd.start();
    }

    /**
     * 取消前贴广告
     */
    public void cancelRequestFrontAdTask() {
        if (mRequestDemandFrontAd != null) {
            mRequestDemandFrontAd.cancel(true);
            mRequestDemandFrontAd = null;
            requestLoading.setVisibility(View.GONE);
        }
    }

    /**
     * 得到前帖广告
     * */
    public synchronized void getDemandFrontAd(int cid, long aid, long vid, String mmsid, String uuid, String uid,
            String vlen, String py, String ty, boolean isSupportM3U8, boolean isNeedPay, boolean disableAvd,
            boolean toShowLoading, boolean isWoOrderUser, boolean isOpenCde) {
        LogInfo.log(TAG, "getDemandFrontAd");
        startRequestFrontAdTask(getActivity(), isWoOrderUser, cid, aid, vid, mmsid, "", uuid, uid, vlen, py, ty,
                isSupportM3U8, isNeedPay, disableAvd, toShowLoading, false, false, isOpenCde, false,false);
    }
    /**
     * 得到前帖广告
     * */
    public synchronized void getDemandFrontAd(int cid, long aid, long vid, String mmsid, String uuid, String uid,
            String vlen, String py, String ty, boolean isSupportM3U8, boolean isNeedPay, boolean disableAvd,
            boolean toShowLoading, boolean isWoOrderUser, boolean isOpenCde,boolean isPanorama) {
        LogInfo.log(TAG, "getDemandFrontAd");
        startRequestFrontAdTask(getActivity(), isWoOrderUser, cid, aid, vid, mmsid, "", uuid, uid, vlen, py, ty,
                isSupportM3U8, isNeedPay, disableAvd, toShowLoading, false, false, isOpenCde, false,isPanorama);
    }
    /**
     * 得到离线的前帖广告
     * 
     * @param cid
     * 频道id
     * @param aid
     * 专辑id
     * @param vid
     * 视频id
     * @param mmsid
     * 媒资id
     * @param uuid
     * 唯一播放id
     * @param uid
     * 用户id
     * @param vlen
     * 视频时长
     * @param py
     * ""
     * @param ty
     * 0
     * @param isVipVideo
     * 是否是试看片 false
     * @param disableAvd
     * 是否禁播avd false
     * @param toShowLoading
     * 是否显示loading false
     * @param isOfflineAds
     * 是否是离线广告 true
     */
    public synchronized void getOfflineFrontAd(int cid, long aid, long vid, String mmsid, String uuid, String uid,
            String vlen, String py, String ty, boolean isVipVideo, boolean disableAvd, boolean toShowLoading,
            boolean isOfflineAds) {
        LogInfo.log(TAG, "getOfflineFrontAd");
        startRequestFrontAdTask(getActivity(), false, cid, aid, vid, mmsid, "", uuid, uid, vlen, py, ty, false,
                isVipVideo, disableAvd, toShowLoading, false, isOfflineAds, false, false,false);
    }

    /**
     * 热点频道得到前帖广告
     * */
    public synchronized void getDemandFrontAdForHot(Context context, int cid, long aid, long vid, String mmsid,
            String uuid, String uid, String vlen, String py, String ty, boolean isSupportM3U8, boolean isNeedPay,
            boolean disableAvd, boolean toShowLoading) {
        LogInfo.log(TAG, "getDemandFrontAdForHot");
        startRequestFrontAdTask(context, false, cid, aid, vid, mmsid, "", uuid, uid, vlen, py, ty, isSupportM3U8,
                isNeedPay, disableAvd, toShowLoading, true, false, false, false,false);
    }

    /**
     * 得到前帖广告
     * */
    public synchronized void getDemandPauseAd(int cid, long aid, long vid, String mmsid, String uuid, String uid,
            String vlen, String py, String ty) {
        LogInfo.log(TAG, "getDemandPauseAd isDestroy=" + isDestroy);
        if (isDestroy) {
            return;
        }
        new RequestDemandPauseAd(getActivity(), cid, aid, vid, mmsid, uuid, uid, vlen, py, ty).start();
    }

    /**
     * 直播前贴广告
     * 
     * @param streamUrl
     * 流
     * @param uuid
     * @param uid
     * @param py
     * @param ty
     * @param toShowLoading
     * @param isWoOrderUser
     * 试看
     * @param isSupportM3U8
     * 是否支持M3U8 开关
     */
    public synchronized void getLiveFrontAd(String streamUrl, String uuid, String uid, String py, String ty,
            boolean toShowLoading, boolean isWoOrderUser, boolean isNeedPay, boolean isSupportM3U8, boolean isUseCde) {
        startTime = System.currentTimeMillis();
        if (isDestroy) {
            return;
        }
        adsPlayCompleteTime = adsLoadingTime = 0;
        loadingStart = System.currentTimeMillis();
        new RequestDemandFrontAd(getActivity(), isWoOrderUser, 0, 0, 0, "0", streamUrl, uuid, uuid,
                "0", py, ty, isSupportM3U8, isNeedPay, false, toShowLoading, false, false,
                isUseCde, true, false)
                .start();
    }

    public synchronized void getLiveFrontAd(String streamUrl, String uuid, String uid, String py,
            String ty, boolean toShowLoading, boolean isWoOrderUser, boolean isNeedPay,
            boolean isSupportM3U8, boolean isUseCde, boolean isPanorama) {
        startTime = System.currentTimeMillis();
        if (isDestroy) {
            return;
        }
        adsPlayCompleteTime = adsLoadingTime = 0;
        loadingStart = System.currentTimeMillis();
        new RequestDemandFrontAd(getActivity(), isWoOrderUser, 0, 0, 0, "0", streamUrl, uuid, uuid,
                "0", py, ty, isSupportM3U8, isNeedPay, false, toShowLoading, false, false,
                isUseCde, true, isPanorama)
                .start();
    }
    /**
     * 开始刷新进度条
     * */
    private void startRefreshTime() {
        handler.removeMessages(MSG_REFRESH_TIME);
        if (!isPauseAd) {
            handler.sendEmptyMessage(MSG_REFRESH_TIME);
        }
    }

    /**
     * 停止刷新进度条
     * */
    private void stopRefreshTime() {
        handler.removeMessages(MSG_REFRESH_TIME);
        handler.removeMessages(HANDLER_REQUEST_URL_TIMEOUT);
    }

    /**
     * 判断是否是横屏
     * */
    public boolean isLandscape() {
        if (getActivity() == null) {
            return false;
        }
        int t = getActivity().getResources().getConfiguration().orientation;
        return t == Configuration.ORIENTATION_LANDSCAPE;

    }

    /**
     * 得到屏幕高度
     * */
    public int getScreenHeight() {
        return ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
    }

    /**
     * 得到屏幕宽度
     * */
    public int getScreenWidth() {
        return ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    }

    /**
     * 将一倍尺寸缩放到当前屏幕大小的尺寸（宽）
     * */
    public int zoomWidth(int w) {
        int sw = 0;
        sw = getScreenWidth();

        return (int) (w * sw / 320f + 0.5f);
    }

    /**
     * 缩放控件
     * */
    public void zoomView(int w, int h, View view) {
        if (view == null) {
            return;
        }

        LayoutParams params = view.getLayoutParams();

        if (params == null) {
            return;
        }

        params.width = zoomWidth(w);
        params.height = zoomWidth(h);
        view.requestLayout();
    }

    /**
     * 缩放控件
     * */
    public void zoomViewFull(View view) {
        if (view == null) {
            return;
        }

        LayoutParams params = view.getLayoutParams();

        if (params == null) {
            return;
        }

        params.width = getScreenWidth();
        params.height = getScreenHeight();
        view.requestLayout();
    }

    /**
     * 前帖播放完成调用
     */
    private void FrontAdFinish() {
        FrontAdFinish(false);
    }

    /**
     * 前帖播放完成调用，恢复布局到初始状态，销毁必要的对象
     * */
    private void FrontAdFinish(boolean isFinishByHand) {
        // finish 调用多次，加入掉用棧分析原因。
        if (Commons.TEST) {
            Exception exception = new Exception("FrontAdFinish");
            exception.printStackTrace();
        }
        LogInfo.log(TAG, "ad finished by " + isFinishByHand);
        LetvLogApiTool.createPlayLogInfo("广告播放结束", videoVid, " 是否需要处理:" + isFinishByHand);
        // isViewCallBack = false;
        isFrontAdProcessing = false;
        AdsManager.getInstance().setFromPush(false);
        mTimeText = -1;
        adsPlayCompleteTime = System.currentTimeMillis();
        adsInteractiveCostTime = adsPlayedTime - loadingStart;
        adsItemIndex = 0;
        adsList = null;
        isPauseAd = false;
        curAdType = NONE;
        totalTime = 0;
        curTime = 0;
        readyToPlayTime = adsPlayedTime = 0;
        isDelayFirstVideoView = true;
        delayAdItem = null;
        isUnionPlay = false;
        if (handler != null) {
            handler.removeMessages(MSG_PREPARE_VIDEO);
            handler.removeMessages(HANDLER_DELAY_LAST_VIDEO);
        }
        if (!isFinishByHand && viewCallBack != null && !isViewCallBack) {// 告诉主客户端,开始缓冲
            isViewCallBack = true;
            viewCallBack.getMainClientBackGroundStart();
        }
        stopCdeBuffer();
        isViewCallBack = false;
        stopRefreshTime();
        handleUI(INVALID_VALUE, PLAY_STATE_COMPLETE, INVALID_VALUE);
        if (mVideoViewFirst != null) {
            mVideoViewFirst.setVisibility(View.GONE);
            mVideoViewFirst.pause();
            mVideoViewFirst.stopPlayback();
        }
        if (mVideoViewSecond != null) {
            mVideoViewSecond.setVisibility(View.GONE);
            mVideoViewSecond.pause();
            mVideoViewSecond.stopPlayback();
        }
        if (letvMediaPlayerControl != null) {
            letvMediaPlayerControl.getView().setVisibility(View.GONE);
            letvMediaPlayerControl.pause();
            letvMediaPlayerControl.stopPlayback();
        }

        if (adListener != null) {
            if (isReady && !isDestroy && !isFinishByHand) {
                if (null != viewCallBack && viewCallBack.getVideoCurrentTime() <= 0) {
                    adListener.onFinish(isFinishByHand);
                }
                if (informer != null) {
                    informer.OnVideoStart(AdsManager.getInstance().isVip());
                }
            }
        }
        notifyAdHadClosed();
        // mPlayAdInfo = null ;
        if (stepsCostTimeArr[0] != 0) {
            CommonAdDataService.writeDebugLog("steps cost time:||" + Arrays.toString(stepsCostTimeArr) + "||");
            stepsCostTimeArr = new long[5];
        }
        isFirstPlayAds = true;
        isPausing = false;

        // adsLoadingTime = 0;
    }

    /**
     * 回调，播放暂停广告 与 TIP 互斥 接口
     */
    public interface PauseAdsListener {
        /**
         * 暂停广告显示回调
         */
        void pauseAdsIsShow();

        /**
         * 关闭暂停广告回调
         */
        void closePauseAdCallBack();
    }

    private PauseAdsListener mPauseAdsListener;

    /**
     * 设置监听
     * 
     * @param mPauseAdsListener
     */
    public void setPauseAdsListener(PauseAdsListener mPauseAdsListener) {
        this.mPauseAdsListener = mPauseAdsListener;
    }

    public Rect getPauseLayoutRect() {
        if (pauseLayout != null) {
            Rect rect = new Rect();
            pauseLayout.getHitRect(rect);
            return rect;
        }
        return null;
    }

    public boolean getIsPauseAdShow() {
        if (pauseLayout != null) {
            return pauseLayout.getVisibility() == View.VISIBLE;
        }
        return false;
    }

    /**
     * 关闭暂停广告
     * */
    public void closePauseAd() {
        LogInfo.log(TAG, "closePauseAd curAdType=" + curAdType + " pauseLayout=" + pauseLayout);
        if (pauseLayout != null && curAdType == PAUSE) {
            LogInfo.log(TAG, "closePauseAd true");
            curAdType = NONE;
            if (mCurAdStatusManager != null) {
                mCurAdStatusManager.onAdClosed();
                mCurAdStatusManager = null;
            }
            pauseLayout.setVisibility(View.GONE);
            if (null != pauseView) {
                // 还原webview的大小
                pauseLayout.setScaleX(1);
                pauseLayout.setScaleY(1);
                pauseView.closeAD();
            }
            if (mPauseAdsListener != null) {
                mPauseAdsListener.closePauseAdCallBack();
            }
        }
    }

    /**
     * 请求完成，处理前帖广告
     * */
    private void handleFondAd(final int videoFormat, final AdElementMime adInfo, final boolean isWoOrderUser, int tag,
            Object... parameters) {
        LetvLogApiTool.createPlayLogInfo("处理广告前贴", "", "视频格式:" + videoFormat + " 是否是联通流量包用户:" + isWoOrderUser
                + " 直播还是点播:" + tag);
        mIsWoOrderUser = isWoOrderUser;
        mTag = tag;
        if (handleInit(adInfo)) {
            return;
        }
        String mediaUrl = null;
        if (FORMAT_M3U8 == videoFormat) {
            LogInfo.log(TAG, "handler-3-8-,iswo:" + isWoOrderUser + ",url=" + parameters + ",tag=" + tag);
            if (null != parameters && parameters.length > 0) {
                SurfaceView surfaceView = (SurfaceView) letvMediaPlayerControl.getView();
                surfaceView.setVisibility(View.VISIBLE);
                surfaceView.requestFocus();
                mediaUrl = (String) parameters[0];
                handleVideoAD(videoFormat, adInfo, mediaUrl, true, true);
            } else {
                FrontAdFinish();
            }
        } else {
            mediaUrl = adInfo.mediaFileUrl;
            if (AdElement.AdMediaType.VIDEO == adInfo.mediaFileType) { // 显示视频广告
                isADShowSucceed = true;
                handleVideoAD(videoFormat, adInfo, mediaUrl, true, true);
            } else if (AdElement.AdMediaType.BITMAP == adInfo.mediaFileType) {// 显示图片广告
                handlePicAD(adInfo, mFrontADImageView);
            } else {
                FrontAdFinish();
            }
        }
        LogInfo.log(TAG, "handleFondAd isWoOrderUser = " + isWoOrderUser + " videoFormat=" + videoFormat + " tag="
                + tag + " mediaUrl=" + mediaUrl);
    }

    private void handlePicAD(final AdElementMime adInfo, final ImageView imageView) {
        if (!TextUtils.isEmpty(adInfo.mediaFileUrl)) {
            ImageDownloader.getInstance(getActivity()).download(adInfo.mediaFileUrl, new ImageDownloadStateListener() {
                @Override
                public void loading() {

                }

                @Override
                public void loadSuccess(Bitmap bitmap) {
                    if (AdElementMime.CuePointType.Pause.value() == adInfo.cuePointType) {
                        pauseLayout.setVisibility(View.VISIBLE);
                        imageView.setImageBitmap(bitmap);
                        exposureStatistics(adInfo);
                        curAdType = PAUSE;
                        if (mPauseAdsListener != null) {
                            mPauseAdsListener.pauseAdsIsShow();
                        }
                    } else if (AdElementMime.CuePointType.PreRoll.value() == adInfo.cuePointType) {
                        isADShowSucceed = true;
                        curAdType = FRONT_JPG;
                        handleUI(adInfo.cuePointType, PLAY_STATE_PLAYING, FRONT_JPG);
                        imageView.setImageBitmap(bitmap);
                        startRefreshTime();
                        mCurAdStatusManager = new AdStatusManager(adInfo);
                        mCurAdStatusManager.onAdLoadComplete((int) (System.currentTimeMillis() - startTime));
                        currentAdElementMime = adInfo;
                        totalTime = adInfo.duration;
                        totalTimeTmp = totalTime;

                        exposureStatistics(adInfo);
                    }
                }

                @Override
                public void loadFailed() {

                }
            });
        }
    }

    private void handleVideoAD(final int videoFormat, final AdElementMime adInfo, String mediaUrl,
            final boolean isFirstFrame, final boolean isFirstVideo) {
        final VideoView videoView;
        if (FORMAT_NORMAL == videoFormat) {
            videoView = isFirstVideo ? mVideoViewFirst : mVideoViewSecond;
        } else {
            videoView = null;
        }
//        if (mIsWoOrderUser && woFlowManager != null) {
//            woFlowManager.identifyWoVideoSDK(getActivity(), mediaUrl, mTag, new WoInterface.LetvWoFlowListener() {
//                @Override
//                public void onResponseOrderInfo(boolean isSupportProvince, boolean isOrder, boolean isUnOrderSure,
//                        final String freeUrl, boolean isSmsSuccess) {
//                    if (!TextUtils.isEmpty(freeUrl)) {
//                        LogInfo.log(TAG, "freeUrl:" + freeUrl);
//                        CommonAdDataService.writeDebugLog("wo url is =" + freeUrl);
//                        LetvLogApiTool.createPlayLogInfo("处理联通流量包广告逻辑", "", "播放地址:" + freeUrl);
//                        if (FORMAT_M3U8 != videoFormat) {
//                            adInfo.mediaFileUrl = freeUrl;
//                        }
//                    }
//                    new Handler(getActivity().getMainLooper()).post(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (FORMAT_M3U8 == videoFormat) {
//                                readyToPlayM3U8(freeUrl);
//                            } else {
//                                if (isFirstFrame) {
//                                    readyToPlayFirstVideo(adInfo);
//                                } else if (null != videoView) {
//                                    setVideoViewParameter(videoView, adInfo.mediaFileUrl, isFirstVideo);
//                                    videoView.requestFocus();
//                                    videoView.start();
//                                }
//                                if (adUrls != null) {
//                                    if (!adUrls.contains(adInfo.mediaFileUrl)) {
//                                        adUrls = adUrls + ";" + adInfo.mediaFileUrl;
//                                    }
//                                } else {
//                                    adUrls = adInfo.mediaFileUrl;
//                                }
//                            }
//                        }
//                    });
//                }
//            });
//        } else {
            if (FORMAT_M3U8 == videoFormat) {
                readyToPlayM3U8(mediaUrl);
            } else {
                if (isFirstFrame) {
                    readyToPlayFirstVideo(adInfo);
                } else if (null != videoView) {
                    setVideoViewParameter(videoView, adInfo.mediaFileUrl, isFirstVideo);
                    videoView.requestFocus();
                    videoView.start();
                }
                if (adUrls != null) {
                    if (!adUrls.contains(adInfo.mediaFileUrl)) {
                        adUrls = adUrls + ";" + adInfo.mediaFileUrl;
                    }
                } else {
                    adUrls = adInfo.mediaFileUrl;
                }
//            }
        }
    }

    /**
     * 准备开始播放非拼接第一个视频
     * 
     * @param adInfo
     */
    private void readyToPlayFirstVideo(final AdElementMime adInfo) {
        boolean su = playFirstVideo(adInfo);
        if (su) {
            currentAdElementMime = adInfo;
            exposureStatistics(adInfo);
            LetvLogApiTool.createPlayLogInfo("开始播放第一个非拼接广告", "-", "素材 :" + adInfo.mediaFileUrl);
        }
    }

    private boolean handleInit(final AdElementMime adInfo) {
        if (!isReady || isDestroy) {
            return true;
        }
        if (adInfo == null) {
            FrontAdFinish();
            return true;
        }
        return false;
    }

    /**
     * 准备开始播放M3U8
     * 
     * @param m3u8VideoUrl
     */
    private void readyToPlayM3U8(String m3u8VideoUrl) {
        blockCount = 0;
        boolean su = playM3U8(m3u8VideoUrl);
        if (su) {
            // handler.sendEmptyMessageDelayed(HANDLER_DELAY_INIT_VIDEO, 2000);
            LogInfo.log(TAG, "play " + su);
            LetvLogApiTool.createPlayLogInfo("开始播放拼接广告", "-", "素材 :" + m3u8VideoUrl);
        }
    }

    /**
     * 请求完成，处理暂停广告
     * */
    private void handlePauseAd(final AdElementMime adInfo) {
        if (adInfo == null) {
            return;
        }
        LogInfo.log(TAG, "handlePauseAd type=" + adInfo.mediaFileType);
        pauseView.setAdMaterialLoadListener(new AdMaterialLoadListener() {

            @Override
            public void onLoadFailed() {
                LogInfo.log(TAG, "handlePauseAd onLoadFailed");
            }

            @Override
            public boolean onLoadComplete() {
                LogInfo.log(TAG, "handlePauseAd onComplete");
                pauseLayout.setVisibility(View.VISIBLE);
                pauseView.setVisibility(View.VISIBLE);
                curAdType = PAUSE;
                if (mPauseAdsListener != null) {
                    mPauseAdsListener.pauseAdsIsShow();
                }
                return true;
            }
        });
        if (AdElement.AdMediaType.HTML == adInfo.mediaFileType) {
            pauseView.setWebEventListener(new AdWebviewEventListener() {
                @Override
                public void onCloseWebView() {
                    pauseDel.performClick();
                    LogInfo.log(TAG, "onCloseWebView");
                }

                @Override
                public void onFullScreen() {
                    LogInfo.log(TAG, "onFullScreen");
                    pauseLayout.setScaleX((float) getScreenWidth() / pauseLayout.getWidth());
                    pauseLayout.setScaleY((float) getScreenHeight() / pauseLayout.getHeight());
                }

                @Override
                public void onRestoreSize() {
                    LogInfo.log(TAG, "onRestoreSize");
                    pauseLayout.setScaleX(1);
                    pauseLayout.setScaleY(1);
                }
            });
        }
        pauseView.showAD(adInfo);
        // if (null != pauseView) {
        // FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        // params.gravity = Gravity.CENTER;
        // if (null == pauseView.getParent()) {
        // LogInfo.log(TAG, "add pause view");
        // pauseLayout.addView(pauseView, 0, params);
        // }
        // // pauseView.setTag(adInfo);
        // // pauseView.setOnClickListener(this);
        // }
    }

    /**
     * 请求点播前帖片广告
     * */
    private class RequestDemandFrontAd extends LetvSimpleAsyncTask<ArrayList<AdElementMime>> {

        private Context mContext;

        private String cid;

        private String aid;

        private String vid;

        private String mmsid;

        private String uuid;

        private String uid;

        private String vlen;

        private String py;

        private String ty;

        private boolean isNeedPay;

        private boolean isSupportM3U8;

        private boolean disableAvd;

        private boolean isHotVideo;

        private boolean isOfflineVideo;

        private String m3u8VideoUrl;

        private boolean isUseCde = false;
        private boolean isLive = false;
        private String streamUrl;
        private boolean isWoOrderUser = false;

        public RequestDemandFrontAd(Context context, boolean isWoOrder, int cid, long aid, long vid, String mmsid,
                String streamUrl, String uuid, String uid, String vlen, String py, String ty, boolean isSupportM3U8,
                boolean isNeedPay, boolean disableAvd, boolean toShowLoading, boolean isHotVideo,
                boolean isOfflineVideo, boolean isOpenCde, boolean isLive,boolean isPanorama) {
            super(context);
            LetvLogApiTool.createPlayLogInfo("开始请求前贴片广告", vid + " ", " 是否是测试环境:"
                    + ConfigurationUtil.getInstance().isDebug + "  cid:" + cid + "  aid:" + aid + "  streamUrl:"
                    + streamUrl + "  uid:" + uid + "  是否支持m3u8:" + isSupportM3U8 + "  是否开启cde:" + isOpenCde
                    + "  是否是热点影片:" + isHotVideo + "  是否是离线视频:" + isOfflineVideo + "  是否是直播:" + isLive + "  是否显示广告:"
                    + AdsManager.getInstance().isShowAd() + "  是否是VIP用户:" + AdsManager.getInstance().isVip());
            // 重置暂停状态
            isPauseAd = false;
            LogInfo.log(TAG, "RequestDemandFrontAd supportM3U8()=" + AdsManager.getInstance().supportM3U8()
                    + "  isWoOrder=" + isWoOrder + " isSupportM3U8=" + isSupportM3U8 + "  isOfflineVideo="
                    + isOfflineVideo + " isOpenCde=" + isOpenCde + "  isLive=" + isLive + " disableAvd=" + disableAvd);
            if (informer != null) {
                informer.destory();
            }
            if (requestLoading != null) {
                requestLoading.setVisibility(toShowLoading ? View.VISIBLE : View.GONE);
            }
            adsRequestTime = System.currentTimeMillis();
            mContext = context.getApplicationContext();
            if (curTask != null)
                curTask.cancel(true);
            curTask = null;
            curTask = this;
            if (adsList != null) {
                adsList.clear();
            }
            totalTime = 0;
            adsItemIndex = 0;
            videoVid = vid + "";
            this.cid = String.valueOf(cid);
            this.aid = String.valueOf(aid);
            this.vid = String.valueOf(vid);
            this.mmsid = mmsid;
            this.uuid = uuid;
            this.uid = uid;
            this.vlen = vlen;
            this.py = py;
            this.ty = ty;
            this.disableAvd = disableAvd;
            LogInfo.log(TAG, "AdsManager.getInstance().cpuSupportLevel=" + AdsManager.getInstance().cpuSupportLevel);
            this.isSupportM3U8 = isSupportM3U8 && AdsManager.getInstance().supportM3U8() && !isWoOrderUser;
            this.isHotVideo = isHotVideo;
            this.isWoOrderUser = isWoOrder;
            this.isUseCde = isOpenCde;
            this.isHotVideo = isHotVideo;
            this.isOfflineVideo = isOfflineVideo;
            this.isLive = isLive;
            this.streamUrl = streamUrl;
            this.isNeedPay = isNeedPay;
            mCurAdStatusManager = null;
        }

        @Override
        public ArrayList<AdElementMime> doInBackground() {
            if (isCancel()) {
                LogInfo.log(TAG, "getDemandFrontAd=--6");
                return null;
            }
            LogInfo.log(TAG, "----------start request front ----isLive=" + isLive + " isOpenCde=" + isUseCde
                    + " isOfflineVideo=" + isOfflineVideo);
            totalTime = totalTimeTmp = 0;
            if (isLive) {
                ArrayList<AdElementMime> list = AdsHttpApi.getLiveFrontAd(context, streamUrl, uuid, uid, py, ty,
                        iPlayerStatusDelegate, false, isNeedPay);
                if (null != list && list.size() > 0) {
                    // 直播只播一个前贴片
                    adsList = new ArrayList<AdElementMime>();
                    adsList.add(list.get(0));
                }
            } else {
                AdInfo frontAd =
                        AdsHttpApi.getFrontAd(mContext.getApplicationContext(), cid, aid, vid, mmsid, uuid, uid, vlen, py, ty,
                        iPlayerStatusDelegate, true, isNeedPay, disableAvd, isHotVideo, isOfflineVideo);
                if (frontAd != null) {
                    adsList = frontAd.adList;
                    setIVideoStatusInformer(frontAd.informer);
                }
            }
            adsRequestTime = System.currentTimeMillis() - adsRequestTime;
            stepsCostTimeArr[0] = adsRequestTime;
            if (adsList != null && adsList.size() > 0) {
                AdElementMime mAdElementMime = null;
                StringBuilder adsUrlSb = new StringBuilder();
                // 拼接使用的字符
                StringBuilder combineStr = new StringBuilder();
                adsVideoRange = new int[adsList.size()];
                for (int i = 0; i < adsList.size(); i++) {
                    mAdElementMime = adsList.get(i);
                    LogInfo.log(TAG, i + "-- mAdElementMime.cuePointType =" + mAdElementMime.cuePointType
                            + "  mAdElementMime.duration =" + mAdElementMime.duration);
                    if (mAdElementMime.cuePointType != AdElement.CuePointType.Standard.value()) {
                        totalTime += mAdElementMime.duration;
                    }
                    adsUrlSb.append(mAdElementMime.mediaFileUrl + ";");
                    if (isSupportM3U8) {
                        combineStr.append(mAdElementMime.mediaFileUrl + "&m3v=1&tss=ios|");
                        adsVideoRange[i] = totalTime * 1000;
                    } else if (!TextUtils.isEmpty(mAdElementMime.localPath)) {
                        // 否则会进行本地替换
                        mAdElementMime.mediaFileUrl = mAdElementMime.localPath;
                    }

                    LogInfo.log(TAG, +i + "-- mAdElementMime.mediaFileUrl =" + mAdElementMime.mediaFileUrl
                            + "  mAdElementMime.duration =" + mAdElementMime.duration);
                }
                LetvLogApiTool.createPlayLogInfo("请求前贴片广告成功", vid + "  ", "  素材(素材之间分号隔开):" + adsUrlSb.toString());
                if (isSupportM3U8 && !isOfflineVideo) {
                    doCdeCombine(combineStr);
                }
                totalTimeTmp = totalTime;
                LogInfo.log("jc666", "totalTimeTmp =" + totalTimeTmp);
            } else {
                LetvLogApiTool.createPlayLogInfo("请求前贴片广告", vid + "  ", "  无返回数据");
            }
            LogInfo.log(TAG, "doinBackGround adsList=" + adsList);
            if (viewCallBack != null) {// 告诉主客户端
                if (null != adsList) {
                    viewCallBack.hasAdsVideos(adsList.size());
                } else {
                    viewCallBack.hasAdsVideos(0);
                }
            }
            LogInfo.log(TAG, "----------end request front ----");
            return adsList;
        }

        private void doCdeCombine(StringBuilder combineStr) {
            isUseCde = isUseCde && CdeHelper.getInstance() != null;
            long curTime = System.currentTimeMillis();
            LogInfo.log(TAG, "begin request combine. start at " + curTime + ",isSupportM3U8=" + isSupportM3U8
                    + "  isUseCde=" + isUseCde);
            LetvLogApiTool.createPlayLogInfo("请求广告拼接服务", vid + "  ", "");
            // 拼接服务
            VideoCombineBean remoteResult = AdsHttpApi.getRemoteCombineResult(combineStr.toString(), null, null,
                    isUseCde);
            LetvLogApiTool.createPlayLogInfo("广告拼接完成", vid, "  url:" + remoteResult.url);
            // 拼接耗时
            adsCombineCostTime = System.currentTimeMillis() - curTime;
            stepsCostTimeArr[1] = adsCombineCostTime;
            LogInfo.log(TAG, "begin request cde. start at " + System.currentTimeMillis() + ",isUseCde=" + isUseCde
                    + "  remoteResult.url=" + remoteResult.url + " remoteResult.m3u8Data=" + remoteResult.m3u8Data);
            if (isUseCde && !TextUtils.isEmpty(remoteResult.m3u8Data)) {
                long cdeBegin = System.currentTimeMillis();
                // 返回拼接内容
                CommonAdDataService.writeDebugLog("use combine and cde ,return m3u8 data is ||" + remoteResult.m3u8Data
                        + ",Cur Time=" + System.currentTimeMillis());
                try {
                    String mCdeM3u8Data = remoteResult.m3u8Data;
                    String mCdeCacheG3Name = adsList.get(0).mediaFileUrl;
                    // LogInfo.log(TAG,"CdeHelper.getInstance()="+CdeHelper.getInstance()+",adsList.get(0)="+adsList.get(0));

                    mCacheUrl = CdeHelper.getInstance().getCacheUrlWithData(mCdeM3u8Data, "m3u8", mCdeCacheG3Name, "");
                    m3u8VideoUrl = CdeHelper.getInstance().getPlayUrl(mCacheUrl); // 给播放器播放
                    LogInfo.log(TAG, "doCdeCombine mCacheUrl=" + mCacheUrl + " m3u8VideoUrl=" + m3u8VideoUrl);
                    LetvLogApiTool.createPlayLogInfo("CDE处理m3u8数据", vid + "  ", "  缓存地址:" + mCacheUrl + "  播放地址:"
                            + m3u8VideoUrl);
                    if (TextUtils.isEmpty(m3u8VideoUrl)) {
                        CommonAdDataService.writeDebugLog("cde error || null url");
                        m3u8VideoUrl = remoteResult.url;
                    }
                    CommonAdDataService.writeDebugLog("return cde url is ||" + m3u8VideoUrl + ",Cur Time="
                            + System.currentTimeMillis());
                } catch (Exception e) {
                    e.printStackTrace();
                    LetvLogApiTool.createPlayLogInfo("CDE处理m3u8数据异常", vid + "  ", e.toString());
                    CommonAdDataService.writeDebugLog("cde error ||" + m3u8VideoUrl);
                    m3u8VideoUrl = remoteResult.url;
                    mCacheUrl = null;
                    isSupportM3U8 = false;
                }
                if (remoteResult.ahsResult != null && remoteResult.ahsResult.size() > 0) {
                    adsList = setAdJoinBean(remoteResult.ahsResult, null);
                }
                stepsCostTimeArr[2] = System.currentTimeMillis() - cdeBegin;
            } else if (!TextUtils.isEmpty(remoteResult.url)) {
                m3u8VideoUrl = remoteResult.url;
                LetvLogApiTool.createPlayLogInfo("没有开启CDE", vid + "  ", "播放地址:" + m3u8VideoUrl);
                CommonAdDataService.writeDebugLog("use combine not cde ,return m3u8 url is ||" + m3u8VideoUrl
                        + ",Cur Time=" + System.currentTimeMillis());
                if (remoteResult.ahsResult != null && remoteResult.ahsResult.size() > 0) {
                    adsList = setAdJoinBean(remoteResult.ahsResult, null);
                }
            } else {
                CommonAdDataService.writeDebugLog("common play ,return m3u8 url is ||" + m3u8VideoUrl + ",Cur Time="
                        + System.currentTimeMillis());
                isSupportM3U8 = false;
            }
        }

        @Override
        public void onPostExecute(ArrayList<AdElementMime> result) {
            LogInfo.log(TAG, "-----onPostExecute-----,isSupportM3U8=" + isSupportM3U8);
            String curNetType = DataUtils.getNetType(mContext.getApplicationContext());
            curTask = null;
            AdElementMime firstAdElementMime = null;
            AdElementMime nextAdElementMime = null;
            if (requestLoading != null) {
                requestLoading.setVisibility(View.GONE);
            }
            if (null == result || result.size() <= 0) {
                if (viewCallBack != null && !isViewCallBack) {// 告诉主客户端,开始缓冲
                    isViewCallBack = true;
                    LogInfo.log(TAG, "result == null or size =0");
                    stopCdeBuffer();
                    viewCallBack.getMainClientBackGroundStart();
                }
                isHaveFrontAds = false;
                FrontAdFinish();
                return;
            } else {
                isHaveFrontAds = true;
                // 如果是离线广告 并且 当前网络状态为非wifi 则提示
                if (isOfflineVideo && (!TextUtils.isEmpty(curNetType) && !curNetType.equals("wifi"))) {
                    Toast m3GToast = Toast.makeText(mContext.getApplicationContext(),
                            getResources().getString(R.string.ad_play_view_text_no_cost), Toast.LENGTH_SHORT);
                    m3GToast.setGravity(Gravity.CENTER, 0, 0);
                    m3GToast.show();
                }
                firstAdElementMime = adsList.get(0);
            }
            if (isCancel() || null == firstAdElementMime) {
                isHaveFrontAds = false;
                FrontAdFinish();
                return;
            }
            adsLoadingTime = System.currentTimeMillis();

            mCurAdStatusManager = new AdStatusManager(firstAdElementMime);
            readyToPlayTime = System.currentTimeMillis();
            if (isSupportM3U8 && !TextUtils.isEmpty(m3u8VideoUrl)) {
                isUnionPlay = true;
                handleFondAd(FORMAT_M3U8, firstAdElementMime, isWoOrderUser, isLive ? TAG_LIVE : TAG_VOD, m3u8VideoUrl);
            } else {
                nextAdElementMime = getNextAdsInfo(result);
                if (nextAdElementMime != null) {
                    prepareNextVideo(nextAdElementMime.mediaFileUrl, false, nextAdElementMime);
                }
                if (null != result || result.size() == 1) {
                    // 用于检测最后一个视频是否缓冲完成,如果完成则通知客户端
                    handler.sendEmptyMessageDelayed(HANDLER_DELAY_LAST_VIDEO, 2000);
                }
                handleFondAd(FORMAT_NORMAL, firstAdElementMime, isWoOrderUser, TAG_VOD, isLive ? TAG_LIVE : TAG_VOD);
            }
        }

        @Override
        public void onPreExecute() {

        }
    }

    /**
     * 请求点播暂停
     * */
    private class RequestDemandPauseAd extends LetvSimpleAsyncTask<AdElementMime> {

        private String cid;

        private String aid;

        private String vid;

        private String mmsid;

        private String uuid;

        private String uid;

        private String vlen;

        private String py;

        private String ty;

        public RequestDemandPauseAd(Context context, int cid, long aid, long vid, String mmsid, String uuid,
                String uid, String vlen, String py, String ty) {
            super(context);
            String fullScreenStr;
            if (null != getActivity()) {
                fullScreenStr = UIController.isLandscape(getActivity()) + "";
            } else {
                fullScreenStr = "Activity 已销毁";
            }
            LetvLogApiTool.createPlayLogInfo("请求暂停广告", vid + "  ", "是否是测试环境:" + ConfigurationUtil.getInstance().isDebug
                    + "  是否显示广告:" + AdsManager.getInstance().isShowAd() + "  是否是VIP用户:"
                    + AdsManager.getInstance().isVip() + "   是否是全屏:" + fullScreenStr);
            if (curTask != null)
                curTask.cancel(true);
            curTask = null;
            curTask = this;
            videoVid = vid + "";
            this.cid = String.valueOf(cid);
            this.aid = String.valueOf(aid);
            this.vid = String.valueOf(vid);
            this.mmsid = mmsid;
            this.uuid = uuid;
            this.uid = uid;
            this.vlen = vlen;
            this.py = py;
            this.ty = ty;
        }

        @Override
        public AdElementMime doInBackground() {

            if (isCancel()) {
                return null;
            }
            ArrayList<AdElementMime> ads = AdsHttpApi.getPauseAd(context, cid, aid, vid, mmsid, uuid, uid, vlen, py,
                    ty, iPlayerStatusDelegate);

            if (ads != null && ads.size() > 0) {
                return ads.get(0);
            }

            return null;
        }

        @Override
        public void onPostExecute(AdElementMime result) {
            curTask = null;
            // mPlayAdInfo = result;
            if (result == null) {
                LogInfo.log(TAG, "result is null");
                LetvLogApiTool.createPlayLogInfo("无暂停广告数据", vid, "...");
                return;
            } else {
                LogInfo.log(TAG, "result.url =" + result.mediaFileUrl);
                LetvLogApiTool.createPlayLogInfo("播放暂停广告", vid + "  ", "mmsid:" + mmsid + "  uuid:" + uuid + "  uid:"
                        + uid + "  素材:" + result.mediaFileUrl);
                handlePauseAd(result);
            }
        }

        @Override
        public void onPreExecute() {
        }
    }

    /**
     * 点击广告跳转到系统浏览器,并请求点击曝光地址和第三方点击曝光地址
     */
    private void clickGotoWeb(AdElementMime info) {
        LogInfo.log(TAG, "clickGotoWeb info=" + info);
        if (null != info) {
            LogInfo.log(TAG, "clickGotoWeb info.url=" + info.mediaFileUrl);
        }
        if (AdsUtils.isNetworkAvailable(getActivity())) {
            if (isUnionPlay) {
                info = adsList.get(adsItemIndex);
            }
            if (info != null
                    && (info.clickShowType == AdElement.AdClickShowType.SHOW_ExternalWebBrowser.value() || info.clickShowType == AdElement.AdClickShowType.SHOW_InternalWebView
                            .value())) {
                if (AdsUtils.checkClickEvent()) {
                    if (!TextUtils.isEmpty(info.getClickThrough())) {
                        AdsUtils.gotoWeb(getActivity(), info);
                        LogInfo.log(TAG, "info.getClickUrl() =" + info.getClickThrough());
                    } else {
                        LogInfo.log(TAG, "info.getClickUrl() is empty!!");
                    }
                }
            } else if (info != null && info.clickShowType == AdElement.AdClickShowType.SHOW_InstallAPK.value()) {
                AdsManager.getInstance().downloadAndInstallApk(info.getClickThrough(), info.text);
            } else {
                // LogInfo.log(TAG, "info xxxx is empty!!");
            }
            clickStatistics(info);
        }
    }

    /**
     * 当前广告曝光统计
     * */
    private void exposureStatistics(AdElementMime info) {
        LogInfo.log(TAG, "exposureStatistics adTag=" + info.adTag + " expose ," + "vast tag=" + info.vastTag
                + " info.url=" + info.mediaFileUrl);
        if (!info.hadExposed) {
            if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
                mCurAdStatusManager = new AdStatusManager(info);
            }
            mCurAdStatusManager.onAdPlayStart();
            info.hadExposed = true;
        }
    }

    /**
     * 当前广告播放完成统计
     * */
    private void completeStatistics(AdElementMime info) {
        LogInfo.log(TAG, "completeStatistics tag=" + info.adTag + " expose ," + "vast tag=" + info.vastTag
                + " info.url=" + info.mediaFileUrl + " info=" + info);
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdPlayComplete();
    }

    /**
     * 广告（当前广告或者缓冲的下一个广告）加载时间统计
     * */
    private void loadTimeStatistics(AdElementMime info, int loadTime, boolean isCurrentAD) {
        LogInfo.log(TAG, "loadtimeStatistics tag=" + info.adTag + " expose ," + "vast tag=" + info.vastTag
                + " info.url=" + info.mediaFileType + " info=" + info + " isCurrentAD=" + isCurrentAD);
        if (isCurrentAD) {
            if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
                mCurAdStatusManager = new AdStatusManager(info);
            }
            mCurAdStatusManager.onAdLoadComplete(loadTime);
        } else {
            if (null == mBufferAdStatusManager || !mBufferAdStatusManager.isSameAD(info)) {
                mBufferAdStatusManager = new AdStatusManager(info);
            }
            mBufferAdStatusManager.onAdLoadComplete(loadTime);
        }
    }

    /**
     * 广告（当前广告或者缓冲的下一个广告）播放错误统计，
     * */
    private void playErrorStatistics(AdElementMime info, boolean isCurrentAD) {
        LogInfo.log(TAG, "adLoadErrorStatistics tag=" + info.adTag + " expose ," + "vast tag=" + info.vastTag
                + " info.url=" + info.mediaFileType + " info=" + info);
        String log = (null != info) ? info.mediaFileUrl : "null";
        LetvLogApiTool.createPlayLogInfo("广告播放错误", videoVid + "  ", "素材:" + log);
        if (isCurrentAD) {
            if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
                mCurAdStatusManager = new AdStatusManager(info);
            }
            mCurAdStatusManager.onAdLoadError();
        } else {
            if (null == mBufferAdStatusManager || !mBufferAdStatusManager.isSameAD(info)) {
                mBufferAdStatusManager = new AdStatusManager(info);
            }
            mBufferAdStatusManager.onAdLoadError();
        }
    }

    /**
     * 当前广告点击上报
     * */
    private void clickStatistics(AdElementMime info) {
        LogInfo.log(TAG, "----------clickStatistics----------");
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdClicked();
    }

    /**
     * 当前广告跳过上报
     * */
    private void skipStatistics(AdElementMime info) {
        LogInfo.log(TAG, "----------skipStatistics----------");
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdSkip();
    }

    /**
     * 当前广告返回上报
     * */
    private void backStatistics(AdElementMime info) {
        LogInfo.log(TAG, "----------backStatistics----------");
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdBack();
    }

    /**
     * 当前广告卡顿上报
     * */
    private void blockStatistics(AdElementMime info) {
        LogInfo.log(TAG, "----------blockStatistics----------");
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdBlock();
    }

    /**
     * 当前广告卡顿结束上报
     * */
    private void blockEndStatistics(AdElementMime info) {
        LogInfo.log(TAG, "----------blockEndStatistics----------");
        if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(info)) {
            mCurAdStatusManager = new AdStatusManager(info);
        }
        mCurAdStatusManager.onAdBlockEnd();
    }

    public interface PlayAdListener {
        /**
         * 广告结束
         *
         * @param isFinishByHand
         * 是否是手动结束
         */
        void onFinish(boolean isFinishByHand);

        /**
         * 广告拼接 m3u8
         *
         * @param ads
         */
        void onM3U8(ArrayList<AdElementMime> ads);

        /**
         * 广告第一次播放
         */
        void onStartPlay();
    }

    public static abstract class VipViewCallBack {
        public abstract void onClick();

        public abstract void ads3G2GClick();

        public abstract int getVideoCurrentTime();

        public abstract void hasAdsVideos(int count);

        public abstract void getMainClientBackGroundStart();

        public abstract void setHalfOrFullScreen(boolean isHalf, boolean isBtnHalf);

        /**
         * 当半屏点退出的时候
         */
        public abstract void onHalfBackDown();

        /**
         * 返回半屏图片推广告给主客户端
         */
        public void onHalfPicADResult(ArrayList<AdElementMime> result) {
        }
    }

    public String getAc() {
        if (isADShowSucceed) {
            return "001_0";
        }

        return "000_0";
    }

    IPlayerStatusDelegate iPlayerStatusDelegate = new IPlayerStatusDelegate() {

        @Override
        public int getVideoCurrentTime() {
            if (viewCallBack != null) {
                return viewCallBack.getVideoCurrentTime();
            }
            return 0;
        }

        @Override
        public int getPlayerCurTime() {
            if (curAdType == FRONT_VIDEO && mCurrentMediaPlayerControl != null) {
                LogInfo.log("ad_m3u8_pro:" + (curTime >= adsPlayedTime * 1000 ? (curTime - adsPlayedTime * 1000) : 0));
                return curTime >= adsPlayedTime * 1000 ? (curTime - adsPlayedTime * 1000) : 0;
            } else if (curAdType == FRONT_JPG) {
                return curTime * 1000;
            }
            return 0;
        }

        @Override
        public Rect getPlayerRect() {
            if (AdsManager.getInstance().getVideoCallBack() != null) {
                return AdsManager.getInstance().getVideoCallBack().getPlayerRect();
            }
            return null;
        }

        @Override
        public void WriteLog(String s, String s2, String s3) {
            try {
                LetvLogApiTool.createPlayLogInfo(s, s2, s3);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void pauseVideo() {
            if (AdsManager.getInstance().getVideoCallBack() != null) {
                AdsManager.getInstance().getVideoCallBack().pauseVideo();
            }
        }

        @Override
        public void resumeVideo() {
            if (AdsManager.getInstance().getVideoCallBack() != null) {
                AdsManager.getInstance().getVideoCallBack().resumeVideo();
            }
        }
    };

    private FFMpegPlayer.OnAdNumberListener onSwitchVideoAdListener = new FFMpegPlayer.OnAdNumberListener() {
        @Override
        public void onAdNumber(FFMpegPlayer ffMpegPlayer, int i) {
            LogInfo.log(TAG, "onAdNumber i=" + i);
            switchVideoAdItem(i);
        }
    };

    /**
     * 播放完成回调
     * */
    private OnCompletionListener onCompletionListenerFirst = new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            handleNormalVideoPlayComplete(true);
        }
    };

    /**
     * 播放完成回调
     * */
    private OnCompletionListener onCompletionListenerSecond = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            handleNormalVideoPlayComplete(false);
        }
    };

    private OnCompletionListener onCompletionListenerM3U8 = new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            LogInfo.log(TAG, "M3U8 complate");
            if (letvMediaPlayerControl != null) {
                letvMediaPlayerControl.stopPlayback();
                letvMediaPlayerControl.getView().setVisibility(View.GONE);
            }
            if (null != adsList && adsList.size() > 0) {
                completeStatistics(adsList.get(adsList.size() - 1));
            }
            FrontAdFinish();
        }
    };

    // 第一条广告是否已经加载完成过
    // private boolean hasPreparedFirst = false;
    /**
     * 准备完成回调
     * */
    private OnPreparedListener mOnPreparedListenerFirst = new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handleVideoPlayPrepare(true, FORMAT_NORMAL);
        }
    };

    /**
     * 准备完成回调
     * */
    private OnPreparedListener mOnPreparedListenerSecond = new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handleVideoPlayPrepare(false, FORMAT_NORMAL);
        }
    };

    private OnPreparedListener mOnPreparedListenerM3U8 = new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handleVideoPlayPrepare(true, FORMAT_M3U8);
        }
    };

    /**
     * 播放错误回调
     * */
    private OnErrorListener mOnErrorListenerFirst = new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            LogInfo.log(TAG, "mOnErrorListenerFirst --error:what:" + what + ",extra:" + extra + ",");
            handleNormalVideoPlayError(true);
            return true;
        }
    };

    /**
     * 播放错误回调
     * */
    private OnErrorListener mOnErrorListenerSecond = new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            LogInfo.log(TAG, "mOnErrorListenerSecond --error:what:" + what + ",extra:" + extra + ",");
            handleNormalVideoPlayError(false);
            return true;
        }
    };

    private OnErrorListener mOnErrorListenerM3U8 = new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            LogInfo.log(TAG, "--error:what:" + what + ",extra:" + extra + ",");
            handleM3U8PlayError();
            return true;
        }
    };

    /**
     * 非拼接视频播放完成处理
     * 
     * @param isFirstVideo
     */
    private void handleNormalVideoPlayComplete(boolean isFirstVideo) {
        LogInfo.log(TAG, "handleVideoPlayComplete isFirstVideo=" + isFirstVideo + " adsItemIndex=" + adsItemIndex);
        AdElementMime completeAdElementMime = null;
        AdElementMime nextAdElementMime = null;
        AdElementMime afterNextAdElementMime = null;
        if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
            completeAdElementMime = adsList.get(adsItemIndex);
            if (completeAdElementMime != null) {
                adsPlayedTime += completeAdElementMime.duration;
                completeStatistics(completeAdElementMime);
            }
            adsItemIndex++;
            LogInfo.log(TAG, "handleVideoPlayComplete adsItemIndex=" + adsItemIndex);
            if (adsList.size() >= (adsItemIndex + 1)) {
                nextAdElementMime = adsList.get(adsItemIndex);
            }
        }
        PrerollVideoView videoView = isFirstVideo ? mVideoViewFirst : mVideoViewSecond;
        if (videoView != null) {
            videoView.stopPlayback();
            videoView.setVisibility(View.GONE);
        }
        if (nextAdElementMime != null) {
            // 一个播放器播放完成,再开始播放下个视频,同时缓冲第后续视频以便提高起播速度
            mCurrentMediaPlayerControl = isFirstVideo ? mVideoViewSecond : mVideoViewFirst;
            startPlayHandler(nextAdElementMime);
            afterNextAdElementMime = getNextAdsInfo(adsList);
            if (afterNextAdElementMime != null) {
                prepareNextVideo(afterNextAdElementMime.mediaFileUrl, isFirstVideo, afterNextAdElementMime);
            }
        } else {
            FrontAdFinish();
        }
        completeAdElementMime = null;
        nextAdElementMime = null;
        afterNextAdElementMime = null;
    }

    private void handleM3U8PlayError() {
        LogInfo.log(TAG, "handleM3U8PlayError adsItemIndex=" + adsItemIndex);
        if (letvMediaPlayerControl != null) {
            letvMediaPlayerControl.pause();
            letvMediaPlayerControl.stopPlayback();
            letvMediaPlayerControl.getView().setVisibility(View.GONE);
        }
        if (handler != null) {
            handler.removeMessages(MSG_PREPARE_VIDEO);
            handler.removeMessages(HANDLER_REQUEST_URL_TIMEOUT);
        }
        AdElementMime currentAD = null;
        if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
            currentAD = adsList.get(adsItemIndex);
            playErrorStatistics(currentAD, true);
        }
        FrontAdFinish();
    }

    /**
     * 处理非拼接视频的播放错误
     * 
     * @param isFirstVideo
     */
    private void handleNormalVideoPlayError(boolean isFirstVideo) {
        LogInfo.log(TAG, "handleNormalVideoPlayError isFirstVideo=" + isFirstVideo + " adsItemIndex=" + adsItemIndex);
        AdElementMime errorAdElementMime = null;
        AdElementMime nextAdElementMime = null;
        AdElementMime afterNextAdElementMime = null;
        PrerollVideoView videoView = isFirstVideo ? mVideoViewFirst : mVideoViewSecond;
        boolean isCurrentADPlayError = (mCurrentMediaPlayerControl == videoView);
        if (videoView != null) {
            videoView.pause();
            videoView.stopPlayback();
            videoView.setVisibility(View.GONE);
        }
        if (handler != null) {
            handler.removeMessages(MSG_PREPARE_VIDEO);
            handler.removeMessages(HANDLER_REQUEST_URL_TIMEOUT);
        }
        if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
            if (isCurrentADPlayError) {
                errorAdElementMime = adsList.get(adsItemIndex);
            } else if (adsList.size() >= (adsItemIndex + 2)) {
                // 当前播放的广告不是发生错误的广告,这是因为缓存下一个广告的导致的.
                errorAdElementMime = adsList.get(adsItemIndex + 1);
                adsList.remove(adsItemIndex + 1);
            }
            if (null != errorAdElementMime) {
                playErrorStatistics(errorAdElementMime, isCurrentADPlayError);
                totalTime = totalTime - errorAdElementMime.duration;
            }
            LogInfo.log(TAG, "handleNormalVideoPlayError adsItemIndex=" + adsItemIndex);
            if (adsList.size() >= (adsItemIndex + 2)) {
                nextAdElementMime = adsList.get(adsItemIndex + 1);
            }
            if (isCurrentADPlayError) {
                adsItemIndex++;
            }
        }
        if (nextAdElementMime != null) {
            whichVideoViewToPlay(isCurrentADPlayError ? !isFirstVideo : isFirstVideo, nextAdElementMime, false);
            afterNextAdElementMime = getNextAdsInfo(adsList);
            if (afterNextAdElementMime != null) {
                prepareNextVideo(afterNextAdElementMime.mediaFileUrl, isFirstVideo, afterNextAdElementMime);
            }
        } else {
            FrontAdFinish();
        }
        errorAdElementMime = null;
        nextAdElementMime = null;
        afterNextAdElementMime = null;
    }

    /**
     * 视频播放准备好之后的处理
     */
    private void handleVideoPlayPrepare(boolean isFirstVideo, int videoFormat) {
        LogInfo.log(TAG, "handleVideoPlayPrepare adsItemIndex=" + adsItemIndex + " isFirstVideo=" + isFirstVideo
                + " videoFormat=" + videoFormat);
        curAdType = FRONT_VIDEO;
        MediaPlayerControl mediaPlayerControl = null;
        if (FORMAT_NORMAL == videoFormat) {
            mediaPlayerControl = isFirstVideo ? mVideoViewFirst : mVideoViewSecond;
        } else {
            mediaPlayerControl = letvMediaPlayerControl;
        }
        if (handler != null) {
            // hasPreparedFirst = true;
            handler.removeMessages(HANDLER_REQUEST_URL_TIMEOUT);
        }
        AdElementMime currentAD = null;
        if (null != adsList && adsList.size() >= (adsItemIndex + 1)) {
            currentAD = adsList.get(adsItemIndex);
            handleUI(currentAD.cuePointType, PLAY_STATE_PLAYING, FRONT_VIDEO);
        }
        // 当前正在播放的mediaControl不是准备播放器的视频(缓冲下一个视频时的情况),则暂停
        boolean isCurrentAD = (mCurrentMediaPlayerControl == mediaPlayerControl);
        LogInfo.log(TAG, "handleVideoPlayPrepare isCurrentAD=" + isCurrentAD + " isPausing=" + isPausing);
        if (!isCurrentAD || isPausing) {
            mediaPlayerControl.pause();
            // 发送下一个视频的加载完成统计
            if (!isCurrentAD) {
                AdElementMime nextAD = null;
                if (null != adsList && adsList.size() >= (adsItemIndex + 2)) {
                    nextAD = adsList.get(adsItemIndex + 1);
                }
                if (nextAD != null) {
                    loadTimeStatistics(nextAD, (int) (System.currentTimeMillis() - startTime), isCurrentAD);
                }
                return;
            }
        } else {
            startRefreshTime();
        }
        /**
         * 加载完成统计
         * */
        if (currentAD != null) {
            loadTimeStatistics(currentAD, (int) (System.currentTimeMillis() - startTime), isCurrentAD);
        }
    }

    private boolean isDelayFirstVideoView = true;
    private AdElementMime delayAdItem;

    /**
     * 准备好下一个非拼接视频的播放状态，便于快速起播
     *
     * @param playUrl
     * @param isFirstVideoView
     * @return
     */
    private boolean prepareNextVideo(final String playUrl, final boolean isFirstVideoView, final AdElementMime adItem) {
        if (!TextUtils.isEmpty(playUrl)) {
            if (handler != null) {
                LogInfo.log(TAG, "prepareVideo isFirstVideoView=" + isFirstVideoView + "  uriString =" + playUrl);
                isDelayFirstVideoView = isFirstVideoView;
                delayAdItem = adItem;
                handler.sendEmptyMessageDelayed(MSG_PREPARE_VIDEO, 2000);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 哪一个播放器开始播放
     * 
     * @param isFirstVideoView
     * @param adItem
     * @param onlyBuffer
     * true 仅仅准备播放状态便于快速起播,准备好之后暂停 ,等待当前视频播放完毕再继续播放. false 正常的播放流程.
     */
    private void whichVideoViewToPlay(final boolean isFirstVideoView, final AdElementMime adItem, boolean onlyBuffer) {
        try {
            LogInfo.log(TAG, "whichVideoViewToPlay isFirstVideoView=" + isFirstVideoView + " onlyPrepare=" + onlyBuffer
                    + " adsItemIndex=" + adsItemIndex);
            if (!onlyBuffer) {
                mCurrentMediaPlayerControl = isFirstVideoView ? mVideoViewFirst : mVideoViewSecond;
                if (null == mCurAdStatusManager || !mCurAdStatusManager.isSameAD(adItem)) {
                    mCurAdStatusManager = new AdStatusManager(adItem);
                }
            } else {
                if (null == mBufferAdStatusManager || !mBufferAdStatusManager.isSameAD(adItem)) {
                    mBufferAdStatusManager = new AdStatusManager(adItem);
                }
            }
            VideoView videoView = isFirstVideoView ? mVideoViewFirst : mVideoViewSecond;
            if (null == videoView) {
                return;
            }
            if (VERSION.SDK_INT >= 11) {// android版本号 小于 11 的特殊处理， 不支持双缓冲
                videoView.setVisibility(View.VISIBLE);
                try {
                    if (VERSION.SDK_INT > 15) {
                        // 如果仅仅是缓冲，最小化该videoview.
                        if (onlyBuffer) {
                            zoomView(1, 1, videoView);
                        } else {
                            if (isLandscape()) {
                                zoomViewFull(videoView);
                            } else {
                                zoomView(320, 180, videoView);
                            }
                        }
                    } else {
                        videoView.setAlpha(onlyBuffer ? 1 : 255);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handleVideoAD(FORMAT_NORMAL, adItem, adItem.mediaFileUrl, false, isFirstVideoView);
                if (!onlyBuffer) {
                    startPlayHandler(adItem);
                }
            } else {
                setVideoViewParameter(videoView, adItem.mediaFileUrl, isFirstVideoView);
                // android版本号 小于 11 的特殊处理， 不支持双缓冲
                if (!onlyBuffer) {
                    videoView.requestFocus();
                    startPlayHandler(adItem);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取下一条广告信息
     *
     * @param result
     * @return
     */
    private AdElementMime getNextAdsInfo(ArrayList<AdElementMime> result) {
        LogInfo.log(TAG, "getNextAdsInfo adsItemIndex=" + adsItemIndex + "  result=" + result);
        if (result != null && result.size() >= adsItemIndex + 2) {
            LogInfo.log(TAG, "result.size() =" + result.size() + "  adsItemIndex =" + adsItemIndex);
            return result.get(adsItemIndex + 1);
        } else {
            // LogInfo.log(TAG, " null ----- " + "  adsItemIndex =" +
            // adsItemIndex);
            return null;
        }
    }

    private void setVideoViewParameter(VideoView videoView, String url, boolean isUseFirstVideoView) {
        videoView.setVideoPath(url);
        videoView.setOnErrorListener(isUseFirstVideoView ? mOnErrorListenerFirst : mOnErrorListenerSecond);
        videoView.setOnPreparedListener(isUseFirstVideoView ? mOnPreparedListenerFirst : mOnPreparedListenerSecond);
        videoView.setOnCompletionListener(isUseFirstVideoView ? onCompletionListenerFirst : onCompletionListenerSecond);
    }

    private void startPlayHandler(final AdElementMime adInfo) {
        if (handleInit(adInfo)) {
            return;
        }
        if (adInfo == null) {
            FrontAdFinish();
            return;
        }
        LogInfo.log(TAG, "startPlayHandler adsItemIndex=" + adsItemIndex);
        currentAdElementMime = adInfo;
        handleUI(adInfo.cuePointType, PLAY_STATE_PLAYING, FRONT_VIDEO);
        if (adsList != null && adsList.size() <= (adsItemIndex + 1)) {
            handler.sendEmptyMessageDelayed(HANDLER_DELAY_LAST_VIDEO, 2000);
        }
        // LogInfo.log(TAG, "xxxxxxx---adInfo---" + adInfo.index);
        if (AdElement.AdMediaType.VIDEO == adInfo.mediaFileType) { // 显示视频广告
            if (null != mCurrentMediaPlayerControl) {
                if (VERSION.SDK_INT > 15) {
                    if (isLandscape()) {
                        zoomViewFull(getCurrentWorkingVideoView());
                    } else {
                        zoomView(320, 180, getCurrentWorkingVideoView());
                    }
                } else {
                    getCurrentWorkingVideoView().setAlpha(1.0f);
                }
                getCurrentWorkingVideoView().setVisibility(View.VISIBLE);
                getCurrentWorkingVideoView().requestFocus();
                mCurrentMediaPlayerControl.start();
                startRefreshTime();
            }
            exposureStatistics(adInfo);
        } else if (AdElement.AdMediaType.BITMAP == adInfo.mediaFileType) {// 显示图片广告
            handlePicAD(adInfo, mFrontADImageView);
        } else {
            FrontAdFinish();
        }
    }

    /**
     * 获取当前播放的videoView
     *
     * @return
     */
    private View getCurrentWorkingVideoView() {
        if (null != mCurrentMediaPlayerControl) {
            if (mCurrentMediaPlayerControl instanceof LetvMediaPlayerControl) {
                return ((LetvMediaPlayerControl) mCurrentMediaPlayerControl).getView();
            } else if (mCurrentMediaPlayerControl instanceof PrerollVideoView) {
                return ((PrerollVideoView) mCurrentMediaPlayerControl);
            }
        }
        return null;
    }

    /**
     *
     * @param ahs
     * 广告拼接结果 广告前贴片
     * @param vs
     * 广告拼接结果 正片
     */
    private ArrayList<AdElementMime> setAdJoinBean(ArrayList<Integer> ahs, String vs) {
        ArrayList<AdElementMime> adListCopy = new ArrayList<AdElementMime>();
        // ArrayList<AdElementMime> errorListCopy = new
        // ArrayList<AdElementMime>();
        if (adsList == null || adsList.size() <= 0) {
            return adsList;
        }
        StringBuffer logBuffer = new StringBuffer();
        if (ahs != null && ahs.size() > 0) {
            if (ahs.size() == adsList.size()) {
                int i = 0;
                for (Integer code : ahs) {
                    AdElementMime item = adsList.get(i);
                    if (code <= 0) {
                        totalTime -= item.duration;
                        logBuffer.append("第").append(i + 1).append("素材:拼接错误 ").append(" , 素材地址:")
                                .append(item.mediaFileUrl).append(" , 素材类型:").append(item.mediaFileType);
                        // errorListCopy.add(item);
                    } else {
                        adListCopy.add(item);
                    }
                    item.errCode = code;
                    ++i;
                }
                LetvLogApiTool.createPlayLogInfo("广告拼接结果", videoVid + "  ", (logBuffer.length() == 0) ? "结果无异常"
                        : logBuffer.toString());
            } else {
                LetvLogApiTool.createPlayLogInfo("广告拼接异常", "...", "ads count is " + adsList.size()
                        + ",but remote count is " + ahs.size());
                LogInfo.log(TAG, "combine fails ,ads count is " + adsList.size() + ",but remote count is " + ahs.size());
            }
            LogInfo.log(TAG, "total count=" + adsList.size() + ",nothing count = " + adListCopy.size());
            if (mCurAdStatusManager == null) {
                new AdStatusManager().onAdLoadError(adsList);// 上传拼接错误广告
            } else {
                mCurAdStatusManager.onAdLoadError(adsList);// 上传拼接错误广告
            }
        }

        return adListCopy;
    }

    /**
     * 新增IVideoStatusInformer ，用于客户端将播放状态通知给广告
     *
     * @return
     */
    public IVideoStatusInformer getIVideoStatusInformer() {
        if (informer != null) {
            return informer;
        }
        return null;
    }

    public void setIVideoStatusInformer(IVideoStatusInformer mIVideoStatusInformer) {
        informer = mIVideoStatusInformer;
    }

    /**
     * 获取广告视频总时长
     *
     * @return
     */
    public int getAdsVideoTotalTime() {
        totalTimeTmp = Math.abs(totalTimeTmp);
        return totalTimeTmp;
    }

    /**
     * 广告加载时长
     *
     * @return
     */
    public long getAdsLoadingTime() {
        // LogInfo.log("request time:"+adsRequestTime);
        return loadTimeInfoFormat(adsRequestTime);
    }

    /**
     * 广告拼接花费时长
     * 
     * @return
     */
    public long getAdsCombineCostTime() {
        return loadTimeInfoFormat(adsCombineCostTime);
    }

    /**
     * 广告加载时长
     *
     * @return
     */
    public long getAdsPlayLoadTime() {
        // LogInfo.log("request load time "+adsLoadingTime);
        return loadTimeInfoFormat(adsLoadingTime);
    }

    /**
     * 广告播放第一帧的时间
     * */
    public long getAdsPlayFirstFrameTime() {
        // LogInfo.log("request first frame:"+adsPlayFirstFrame);

        return adsPlayFirstFrame;
    }

    /**
     * 广告播放完毕的时间
     * */
    public long getAdsPlayCompleteTime() {
        return adsPlayCompleteTime;
    }

    /**
     * 获取广告实际播放时长
     * 
     * @return
     */
    public long getAdsCostPlayTimeInFact() {
        if (adsPlayFirstFrame == 0) {
            return 0;
        }
        if (adsPlayCompleteTime == 0) {
            adsPlayCompleteTime = System.currentTimeMillis();
        }
        LogInfo.log(TAG, "adsPlayCompleteTime=" + adsPlayCompleteTime + ",adsPlayFirstFrame" + adsPlayFirstFrame
                + ",sum=" + (adsPlayFirstFrame - adsPlayCompleteTime));

        return loadTimeInfoFormat(adsPlayCompleteTime - adsPlayFirstFrame);
    }

    /**
     * 广告交互时长
     * 
     * @return
     */
    public long getAdsInteractiveTimeInFact() {
        return loadTimeInfoFormat(adsInteractiveCostTime);
    }

    /**
     * 返回广告播放地址
     * */
    public String getAdUrls() {
        return adUrls;
    }

    /**
     * 格式化时间
     * 
     * @param time
     * @return
     */
    private long loadTimeInfoFormat(long time) {
        if (time < 0)
            time = 0;
        return (time > 575990000) ? (System.currentTimeMillis() - time) : time;
    }

    public boolean isLockedScreen() {
        return isLockedScreen;
    }

    public void setLockedScreen(boolean isLockedScreen) {
        this.isLockedScreen = isLockedScreen;
    }

    /**
     * 是否播完广告。未播放广告时返回true，否则返回false
     * 
     * @return
     */
    public boolean isFinishAd() {
        return mCurAdStatusManager == null;
    }

    private class RequestCdeInterface extends LetvSimpleAsyncTask<String> {

        private String mUrl;

        public RequestCdeInterface(Context context, String url) {
            super(context);
            mUrl = url;
        }

        @Override
        public void onPreExecute() {

        }

        @Override
        public String doInBackground() {
            if (isCancel())
                return null;
            LogInfo.log(TAG, "doInBackground mUrl=" + mUrl);
            String cdeStopResult = CommonAdDataService.get(mUrl);
            return cdeStopResult;
        }

        @Override
        public void onPostExecute(String result) {
            LogInfo.log(TAG, "stop cde ... result is " + result);
        }
    }

    /**
     * 停止CDE
     */
    private void stopCdeBuffer() {
        LogInfo.log(TAG, "stop cde ... mCacheUrl=" + mCacheUrl);
        if (null != CdeHelper.getInstance()) {
            boolean isCdeReady = CdeHelper.getInstance().isReady();
            LogInfo.log(TAG, "stopCdeBuffer,isCdeReady=" + isCdeReady);
            try {
                if (!TextUtils.isEmpty(mCacheUrl) && isCdeReady) {
                    try {
                        new RequestCdeInterface(getActivity(), CdeHelper.getInstance().getStopUrl(mCacheUrl)).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            LogInfo.log(TAG, "stopCdeBuffer,cde is null");
        }
        mCacheUrl = null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.pause_del == id) {
            closePauseAd();
        } else if (R.id.ad_mute == id) {
            int cur = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (cur == 0) {
                if (oldVolume == 0) {// 无声音，且上一次的声音也为0，那么给一个初始值
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);
                    muteView.setImageResource(R.drawable.letv_ad_not_muted);
                } else {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, oldVolume, 0);
                    muteView.setImageResource(R.drawable.letv_ad_not_muted);
                }
            } else {
                oldVolume = cur;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                muteView.setImageResource(R.drawable.letv_ad_mute);
                mVideoViewFirst.setVoice(0, getActivity(), audioManager);

            }
        } else if (R.id.ad_image == id || R.id.ad_details == id || v == pauseView) {
            if (null != currentAdElementMime) {
                clickGotoWeb(currentAdElementMime);
            }
        } else if (R.id.ad_vip == id) {
            // 会员去广告按钮，点击回调主工程
            if (viewCallBack != null) {
                viewCallBack.onClick();
                if (null != currentAdElementMime) {
                    skipStatistics(currentAdElementMime);
                }
            }
        } else if (R.id.wifiTopViewHalfAd == id) {
            // 3G/2G
            // 点击继续播放
            if (viewCallBack != null) {
                viewCallBack.ads3G2GClick();
            }
            if (vipView != null) {
//                vipView.setVisibility(View.VISIBLE);
            }
            if (adsBottomView != null) {
                adsBottomView.setVisibility(View.VISIBLE);
            }
        } else if (R.id.ad_view_disp == id) {
            // 全屏半屏切换
            if (viewCallBack != null) {
                viewCallBack.setHalfOrFullScreen(!isLandscape(), true);
            }
        } else if (R.id.ad_view_back == id) {
            // 全屏按返回键返回半屏
            if (viewCallBack != null) {
                if (isLandscape()) {
                    viewCallBack.setHalfOrFullScreen(false, false);
                } else {
                    if (null != currentAdElementMime) {
                        backStatistics(currentAdElementMime);
                    }
                    viewCallBack.onHalfBackDown();
                }
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int id = v.getId();
        if (R.id.ad_video_click == id && event.getAction() == MotionEvent.ACTION_UP) {
            // 左右边距
            float horizontalMargin = getResources().getDimension(R.dimen.hot_area_horizontal_margin);
            // 上下边距
            float verticalMargin = getResources().getDimension(R.dimen.hot_area_vertical_margin);
            if (event.getX() >= horizontalMargin && event.getX() <= (v.getWidth() - horizontalMargin)
                    && event.getY() >= verticalMargin && event.getY() <= (v.getHeight() - verticalMargin)) {
                if (null != currentAdElementMime) {
                    clickGotoWeb(currentAdElementMime);
                }
            }
        }
        return false;
    }
}
